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 Base64Test
@Test public void testDecodeWithInnerPad() { final String content = "SGVsbG8gV29ybGQ=SGVsbG8gV29ybGQ="; final byte[] result = Base64.decodeBase64(content); final byte[] shouldBe = StringUtils.getBytesUtf8("Hello World"); assertTrue("decode should halt at pad (=)", Arrays.equals(result, shouldBe)); }
// public Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe); // public boolean isUrlSafe(); // @Override // void encode(final byte[] in, int inPos, final int inAvail, final Context context); // @Override // void decode(final byte[] in, int inPos, final int inAvail, final Context context); // @Deprecated // public static boolean isArrayByteBase64(final byte[] arrayOctet); // public static boolean isBase64(final byte octet); // public static boolean isBase64(final String base64); // public static boolean isBase64(final byte[] arrayOctet); // public static byte[] encodeBase64(final byte[] binaryData); // public static String encodeBase64String(final byte[] binaryData); // public static byte[] encodeBase64URLSafe(final byte[] binaryData); // public static String encodeBase64URLSafeString(final byte[] binaryData); // public static byte[] encodeBase64Chunked(final byte[] binaryData); // public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked); // public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe); // public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, // final boolean urlSafe, final int maxResultSize); // public static byte[] decodeBase64(final String base64String); // public static byte[] decodeBase64(final byte[] base64Data); // public static BigInteger decodeInteger(final byte[] pArray); // public static byte[] encodeInteger(final BigInteger bigInt); // static byte[] toIntegerBytes(final BigInteger bigInt); // @Override // protected boolean isInAlphabet(final byte octet); // } // // // Abstract Java Test Class // package org.apache.commons.codec.binary; // // 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.math.BigInteger; // import java.nio.charset.Charset; // import java.util.Arrays; // import java.util.Random; // import org.apache.commons.codec.Charsets; // import org.apache.commons.codec.DecoderException; // import org.apache.commons.codec.EncoderException; // import org.apache.commons.lang3.ArrayUtils; // import org.junit.Ignore; // import org.junit.Test; // // // // public class Base64Test { // private static final Charset CHARSET_UTF8 = Charsets.UTF_8; // private final Random random = new Random(); // // public Random getRandom(); // @Test // public void testIsStringBase64(); // @Test // public void testBase64(); // @Test // public void testBase64AtBufferStart(); // @Test // public void testBase64AtBufferEnd(); // @Test // public void testBase64AtBufferMiddle(); // private void testBase64InBuffer(int startPasSize, int endPadSize); // @Test // public void testDecodeWithInnerPad(); // @Test // public void testChunkedEncodeMultipleOf76(); // @Test // public void testCodec68(); // @Test // public void testCodeInteger1(); // @Test // public void testCodeInteger2(); // @Test // public void testCodeInteger3(); // @Test // public void testCodeInteger4(); // @Test // public void testCodeIntegerEdgeCases(); // @Test // public void testCodeIntegerNull(); // @Test // public void testConstructors(); // @Test // public void testConstructor_Int_ByteArray_Boolean(); // @Test // public void testConstructor_Int_ByteArray_Boolean_UrlSafe(); // @Test // public void testDecodePadMarkerIndex2(); // @Test // public void testDecodePadMarkerIndex3(); // @Test // public void testDecodePadOnly(); // @Test // public void testDecodePadOnlyChunked(); // @Test // public void testDecodeWithWhitespace() throws Exception; // @Test // public void testEmptyBase64(); // @Test // public void testEncodeDecodeRandom(); // @Test // public void testEncodeDecodeSmall(); // @Test // public void testEncodeOverMaxSize() throws Exception; // @Test // public void testCodec112(); // private void testEncodeOverMaxSize(final int maxSize) throws Exception; // @Test // public void testIgnoringNonBase64InDecode() throws Exception; // @Test // public void testIsArrayByteBase64(); // @Test // public void testIsUrlSafe(); // @Test // public void testKnownDecodings(); // @Test // public void testKnownEncodings(); // @Test // public void testNonBase64Test() throws Exception; // @Test // public void testObjectDecodeWithInvalidParameter() throws Exception; // @Test // public void testObjectDecodeWithValidParameter() throws Exception; // @Test // public void testObjectEncodeWithInvalidParameter() throws Exception; // @Test // public void testObjectEncodeWithValidParameter() throws Exception; // @Test // public void testObjectEncode() throws Exception; // @Test // public void testPairs(); // @Test // public void testRfc2045Section2Dot1CrLfDefinition(); // @Test // public void testRfc2045Section6Dot8ChunkSizeDefinition(); // @Test // public void testRfc1421Section6Dot8ChunkSizeDefinition(); // @Test // public void testRfc4648Section10Decode(); // @Test // public void testRfc4648Section10DecodeWithCrLf(); // @Test // public void testRfc4648Section10Encode(); // @Test // public void testRfc4648Section10DecodeEncode(); // private void testDecodeEncode(final String encodedText); // @Test // public void testRfc4648Section10EncodeDecode(); // private void testEncodeDecode(final String plainText); // @Test // public void testSingletons(); // @Test // public void testSingletonsChunked(); // @Test // public void testTriplets(); // @Test // public void testTripletsChunked(); // @Test // public void testUrlSafe(); // @Test // public void testUUID() throws DecoderException; // @Test // public void testByteToStringVariations() throws DecoderException; // @Test // public void testStringToByteVariations() throws DecoderException; // private String toString(final byte[] data); // @Test // @Ignore // public void testHugeLineSeparator(); // } // You are a professional Java test case writer, please create a test case named `testDecodeWithInnerPad` for the `Base64` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test our decode with pad character in the middle. (Our current * implementation: halt decode and return what we've got so far). * * The point of this test is not to say * "this is the correct way to decode base64." The point is simply to keep * us aware of the current logic since 1.4 so we don't accidentally break it * without realizing. * * Note for historians. The 1.3 logic would decode to: * "Hello World\u0000Hello World" -- null in the middle --- and 1.4 * unwittingly changed it to current logic. */
src/test/java/org/apache/commons/codec/binary/Base64Test.java
package org.apache.commons.codec.binary; import java.math.BigInteger;
public Base64(); public Base64(final boolean urlSafe); public Base64(final int lineLength); public Base64(final int lineLength, final byte[] lineSeparator); public Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe); public boolean isUrlSafe(); @Override void encode(final byte[] in, int inPos, final int inAvail, final Context context); @Override void decode(final byte[] in, int inPos, final int inAvail, final Context context); @Deprecated public static boolean isArrayByteBase64(final byte[] arrayOctet); public static boolean isBase64(final byte octet); public static boolean isBase64(final String base64); public static boolean isBase64(final byte[] arrayOctet); public static byte[] encodeBase64(final byte[] binaryData); public static String encodeBase64String(final byte[] binaryData); public static byte[] encodeBase64URLSafe(final byte[] binaryData); public static String encodeBase64URLSafeString(final byte[] binaryData); public static byte[] encodeBase64Chunked(final byte[] binaryData); public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked); public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe); public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe, final int maxResultSize); public static byte[] decodeBase64(final String base64String); public static byte[] decodeBase64(final byte[] base64Data); public static BigInteger decodeInteger(final byte[] pArray); public static byte[] encodeInteger(final BigInteger bigInt); static byte[] toIntegerBytes(final BigInteger bigInt); @Override protected boolean isInAlphabet(final byte octet);
156
testDecodeWithInnerPad
```java public Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe); public boolean isUrlSafe(); @Override void encode(final byte[] in, int inPos, final int inAvail, final Context context); @Override void decode(final byte[] in, int inPos, final int inAvail, final Context context); @Deprecated public static boolean isArrayByteBase64(final byte[] arrayOctet); public static boolean isBase64(final byte octet); public static boolean isBase64(final String base64); public static boolean isBase64(final byte[] arrayOctet); public static byte[] encodeBase64(final byte[] binaryData); public static String encodeBase64String(final byte[] binaryData); public static byte[] encodeBase64URLSafe(final byte[] binaryData); public static String encodeBase64URLSafeString(final byte[] binaryData); public static byte[] encodeBase64Chunked(final byte[] binaryData); public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked); public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe); public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe, final int maxResultSize); public static byte[] decodeBase64(final String base64String); public static byte[] decodeBase64(final byte[] base64Data); public static BigInteger decodeInteger(final byte[] pArray); public static byte[] encodeInteger(final BigInteger bigInt); static byte[] toIntegerBytes(final BigInteger bigInt); @Override protected boolean isInAlphabet(final byte octet); } // Abstract Java Test Class package org.apache.commons.codec.binary; 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.math.BigInteger; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Random; import org.apache.commons.codec.Charsets; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.EncoderException; import org.apache.commons.lang3.ArrayUtils; import org.junit.Ignore; import org.junit.Test; public class Base64Test { private static final Charset CHARSET_UTF8 = Charsets.UTF_8; private final Random random = new Random(); public Random getRandom(); @Test public void testIsStringBase64(); @Test public void testBase64(); @Test public void testBase64AtBufferStart(); @Test public void testBase64AtBufferEnd(); @Test public void testBase64AtBufferMiddle(); private void testBase64InBuffer(int startPasSize, int endPadSize); @Test public void testDecodeWithInnerPad(); @Test public void testChunkedEncodeMultipleOf76(); @Test public void testCodec68(); @Test public void testCodeInteger1(); @Test public void testCodeInteger2(); @Test public void testCodeInteger3(); @Test public void testCodeInteger4(); @Test public void testCodeIntegerEdgeCases(); @Test public void testCodeIntegerNull(); @Test public void testConstructors(); @Test public void testConstructor_Int_ByteArray_Boolean(); @Test public void testConstructor_Int_ByteArray_Boolean_UrlSafe(); @Test public void testDecodePadMarkerIndex2(); @Test public void testDecodePadMarkerIndex3(); @Test public void testDecodePadOnly(); @Test public void testDecodePadOnlyChunked(); @Test public void testDecodeWithWhitespace() throws Exception; @Test public void testEmptyBase64(); @Test public void testEncodeDecodeRandom(); @Test public void testEncodeDecodeSmall(); @Test public void testEncodeOverMaxSize() throws Exception; @Test public void testCodec112(); private void testEncodeOverMaxSize(final int maxSize) throws Exception; @Test public void testIgnoringNonBase64InDecode() throws Exception; @Test public void testIsArrayByteBase64(); @Test public void testIsUrlSafe(); @Test public void testKnownDecodings(); @Test public void testKnownEncodings(); @Test public void testNonBase64Test() throws Exception; @Test public void testObjectDecodeWithInvalidParameter() throws Exception; @Test public void testObjectDecodeWithValidParameter() throws Exception; @Test public void testObjectEncodeWithInvalidParameter() throws Exception; @Test public void testObjectEncodeWithValidParameter() throws Exception; @Test public void testObjectEncode() throws Exception; @Test public void testPairs(); @Test public void testRfc2045Section2Dot1CrLfDefinition(); @Test public void testRfc2045Section6Dot8ChunkSizeDefinition(); @Test public void testRfc1421Section6Dot8ChunkSizeDefinition(); @Test public void testRfc4648Section10Decode(); @Test public void testRfc4648Section10DecodeWithCrLf(); @Test public void testRfc4648Section10Encode(); @Test public void testRfc4648Section10DecodeEncode(); private void testDecodeEncode(final String encodedText); @Test public void testRfc4648Section10EncodeDecode(); private void testEncodeDecode(final String plainText); @Test public void testSingletons(); @Test public void testSingletonsChunked(); @Test public void testTriplets(); @Test public void testTripletsChunked(); @Test public void testUrlSafe(); @Test public void testUUID() throws DecoderException; @Test public void testByteToStringVariations() throws DecoderException; @Test public void testStringToByteVariations() throws DecoderException; private String toString(final byte[] data); @Test @Ignore public void testHugeLineSeparator(); } ``` You are a professional Java test case writer, please create a test case named `testDecodeWithInnerPad` for the `Base64` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test our decode with pad character in the middle. (Our current * implementation: halt decode and return what we've got so far). * * The point of this test is not to say * "this is the correct way to decode base64." The point is simply to keep * us aware of the current logic since 1.4 so we don't accidentally break it * without realizing. * * Note for historians. The 1.3 logic would decode to: * "Hello World\u0000Hello World" -- null in the middle --- and 1.4 * unwittingly changed it to current logic. */
150
// public Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe); // public boolean isUrlSafe(); // @Override // void encode(final byte[] in, int inPos, final int inAvail, final Context context); // @Override // void decode(final byte[] in, int inPos, final int inAvail, final Context context); // @Deprecated // public static boolean isArrayByteBase64(final byte[] arrayOctet); // public static boolean isBase64(final byte octet); // public static boolean isBase64(final String base64); // public static boolean isBase64(final byte[] arrayOctet); // public static byte[] encodeBase64(final byte[] binaryData); // public static String encodeBase64String(final byte[] binaryData); // public static byte[] encodeBase64URLSafe(final byte[] binaryData); // public static String encodeBase64URLSafeString(final byte[] binaryData); // public static byte[] encodeBase64Chunked(final byte[] binaryData); // public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked); // public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe); // public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, // final boolean urlSafe, final int maxResultSize); // public static byte[] decodeBase64(final String base64String); // public static byte[] decodeBase64(final byte[] base64Data); // public static BigInteger decodeInteger(final byte[] pArray); // public static byte[] encodeInteger(final BigInteger bigInt); // static byte[] toIntegerBytes(final BigInteger bigInt); // @Override // protected boolean isInAlphabet(final byte octet); // } // // // Abstract Java Test Class // package org.apache.commons.codec.binary; // // 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.math.BigInteger; // import java.nio.charset.Charset; // import java.util.Arrays; // import java.util.Random; // import org.apache.commons.codec.Charsets; // import org.apache.commons.codec.DecoderException; // import org.apache.commons.codec.EncoderException; // import org.apache.commons.lang3.ArrayUtils; // import org.junit.Ignore; // import org.junit.Test; // // // // public class Base64Test { // private static final Charset CHARSET_UTF8 = Charsets.UTF_8; // private final Random random = new Random(); // // public Random getRandom(); // @Test // public void testIsStringBase64(); // @Test // public void testBase64(); // @Test // public void testBase64AtBufferStart(); // @Test // public void testBase64AtBufferEnd(); // @Test // public void testBase64AtBufferMiddle(); // private void testBase64InBuffer(int startPasSize, int endPadSize); // @Test // public void testDecodeWithInnerPad(); // @Test // public void testChunkedEncodeMultipleOf76(); // @Test // public void testCodec68(); // @Test // public void testCodeInteger1(); // @Test // public void testCodeInteger2(); // @Test // public void testCodeInteger3(); // @Test // public void testCodeInteger4(); // @Test // public void testCodeIntegerEdgeCases(); // @Test // public void testCodeIntegerNull(); // @Test // public void testConstructors(); // @Test // public void testConstructor_Int_ByteArray_Boolean(); // @Test // public void testConstructor_Int_ByteArray_Boolean_UrlSafe(); // @Test // public void testDecodePadMarkerIndex2(); // @Test // public void testDecodePadMarkerIndex3(); // @Test // public void testDecodePadOnly(); // @Test // public void testDecodePadOnlyChunked(); // @Test // public void testDecodeWithWhitespace() throws Exception; // @Test // public void testEmptyBase64(); // @Test // public void testEncodeDecodeRandom(); // @Test // public void testEncodeDecodeSmall(); // @Test // public void testEncodeOverMaxSize() throws Exception; // @Test // public void testCodec112(); // private void testEncodeOverMaxSize(final int maxSize) throws Exception; // @Test // public void testIgnoringNonBase64InDecode() throws Exception; // @Test // public void testIsArrayByteBase64(); // @Test // public void testIsUrlSafe(); // @Test // public void testKnownDecodings(); // @Test // public void testKnownEncodings(); // @Test // public void testNonBase64Test() throws Exception; // @Test // public void testObjectDecodeWithInvalidParameter() throws Exception; // @Test // public void testObjectDecodeWithValidParameter() throws Exception; // @Test // public void testObjectEncodeWithInvalidParameter() throws Exception; // @Test // public void testObjectEncodeWithValidParameter() throws Exception; // @Test // public void testObjectEncode() throws Exception; // @Test // public void testPairs(); // @Test // public void testRfc2045Section2Dot1CrLfDefinition(); // @Test // public void testRfc2045Section6Dot8ChunkSizeDefinition(); // @Test // public void testRfc1421Section6Dot8ChunkSizeDefinition(); // @Test // public void testRfc4648Section10Decode(); // @Test // public void testRfc4648Section10DecodeWithCrLf(); // @Test // public void testRfc4648Section10Encode(); // @Test // public void testRfc4648Section10DecodeEncode(); // private void testDecodeEncode(final String encodedText); // @Test // public void testRfc4648Section10EncodeDecode(); // private void testEncodeDecode(final String plainText); // @Test // public void testSingletons(); // @Test // public void testSingletonsChunked(); // @Test // public void testTriplets(); // @Test // public void testTripletsChunked(); // @Test // public void testUrlSafe(); // @Test // public void testUUID() throws DecoderException; // @Test // public void testByteToStringVariations() throws DecoderException; // @Test // public void testStringToByteVariations() throws DecoderException; // private String toString(final byte[] data); // @Test // @Ignore // public void testHugeLineSeparator(); // } // You are a professional Java test case writer, please create a test case named `testDecodeWithInnerPad` for the `Base64` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test our decode with pad character in the middle. (Our current * implementation: halt decode and return what we've got so far). * * The point of this test is not to say * "this is the correct way to decode base64." The point is simply to keep * us aware of the current logic since 1.4 so we don't accidentally break it * without realizing. * * Note for historians. The 1.3 logic would decode to: * "Hello World\u0000Hello World" -- null in the middle --- and 1.4 * unwittingly changed it to current logic. */ @Test public void testDecodeWithInnerPad() {
/** * Test our decode with pad character in the middle. (Our current * implementation: halt decode and return what we've got so far). * * The point of this test is not to say * "this is the correct way to decode base64." The point is simply to keep * us aware of the current logic since 1.4 so we don't accidentally break it * without realizing. * * Note for historians. The 1.3 logic would decode to: * "Hello World\u0000Hello World" -- null in the middle --- and 1.4 * unwittingly changed it to current logic. */
18
org.apache.commons.codec.binary.Base64
src/test/java
```java public Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe); public boolean isUrlSafe(); @Override void encode(final byte[] in, int inPos, final int inAvail, final Context context); @Override void decode(final byte[] in, int inPos, final int inAvail, final Context context); @Deprecated public static boolean isArrayByteBase64(final byte[] arrayOctet); public static boolean isBase64(final byte octet); public static boolean isBase64(final String base64); public static boolean isBase64(final byte[] arrayOctet); public static byte[] encodeBase64(final byte[] binaryData); public static String encodeBase64String(final byte[] binaryData); public static byte[] encodeBase64URLSafe(final byte[] binaryData); public static String encodeBase64URLSafeString(final byte[] binaryData); public static byte[] encodeBase64Chunked(final byte[] binaryData); public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked); public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe); public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe, final int maxResultSize); public static byte[] decodeBase64(final String base64String); public static byte[] decodeBase64(final byte[] base64Data); public static BigInteger decodeInteger(final byte[] pArray); public static byte[] encodeInteger(final BigInteger bigInt); static byte[] toIntegerBytes(final BigInteger bigInt); @Override protected boolean isInAlphabet(final byte octet); } // Abstract Java Test Class package org.apache.commons.codec.binary; 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.math.BigInteger; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Random; import org.apache.commons.codec.Charsets; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.EncoderException; import org.apache.commons.lang3.ArrayUtils; import org.junit.Ignore; import org.junit.Test; public class Base64Test { private static final Charset CHARSET_UTF8 = Charsets.UTF_8; private final Random random = new Random(); public Random getRandom(); @Test public void testIsStringBase64(); @Test public void testBase64(); @Test public void testBase64AtBufferStart(); @Test public void testBase64AtBufferEnd(); @Test public void testBase64AtBufferMiddle(); private void testBase64InBuffer(int startPasSize, int endPadSize); @Test public void testDecodeWithInnerPad(); @Test public void testChunkedEncodeMultipleOf76(); @Test public void testCodec68(); @Test public void testCodeInteger1(); @Test public void testCodeInteger2(); @Test public void testCodeInteger3(); @Test public void testCodeInteger4(); @Test public void testCodeIntegerEdgeCases(); @Test public void testCodeIntegerNull(); @Test public void testConstructors(); @Test public void testConstructor_Int_ByteArray_Boolean(); @Test public void testConstructor_Int_ByteArray_Boolean_UrlSafe(); @Test public void testDecodePadMarkerIndex2(); @Test public void testDecodePadMarkerIndex3(); @Test public void testDecodePadOnly(); @Test public void testDecodePadOnlyChunked(); @Test public void testDecodeWithWhitespace() throws Exception; @Test public void testEmptyBase64(); @Test public void testEncodeDecodeRandom(); @Test public void testEncodeDecodeSmall(); @Test public void testEncodeOverMaxSize() throws Exception; @Test public void testCodec112(); private void testEncodeOverMaxSize(final int maxSize) throws Exception; @Test public void testIgnoringNonBase64InDecode() throws Exception; @Test public void testIsArrayByteBase64(); @Test public void testIsUrlSafe(); @Test public void testKnownDecodings(); @Test public void testKnownEncodings(); @Test public void testNonBase64Test() throws Exception; @Test public void testObjectDecodeWithInvalidParameter() throws Exception; @Test public void testObjectDecodeWithValidParameter() throws Exception; @Test public void testObjectEncodeWithInvalidParameter() throws Exception; @Test public void testObjectEncodeWithValidParameter() throws Exception; @Test public void testObjectEncode() throws Exception; @Test public void testPairs(); @Test public void testRfc2045Section2Dot1CrLfDefinition(); @Test public void testRfc2045Section6Dot8ChunkSizeDefinition(); @Test public void testRfc1421Section6Dot8ChunkSizeDefinition(); @Test public void testRfc4648Section10Decode(); @Test public void testRfc4648Section10DecodeWithCrLf(); @Test public void testRfc4648Section10Encode(); @Test public void testRfc4648Section10DecodeEncode(); private void testDecodeEncode(final String encodedText); @Test public void testRfc4648Section10EncodeDecode(); private void testEncodeDecode(final String plainText); @Test public void testSingletons(); @Test public void testSingletonsChunked(); @Test public void testTriplets(); @Test public void testTripletsChunked(); @Test public void testUrlSafe(); @Test public void testUUID() throws DecoderException; @Test public void testByteToStringVariations() throws DecoderException; @Test public void testStringToByteVariations() throws DecoderException; private String toString(final byte[] data); @Test @Ignore public void testHugeLineSeparator(); } ``` You are a professional Java test case writer, please create a test case named `testDecodeWithInnerPad` for the `Base64` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test our decode with pad character in the middle. (Our current * implementation: halt decode and return what we've got so far). * * The point of this test is not to say * "this is the correct way to decode base64." The point is simply to keep * us aware of the current logic since 1.4 so we don't accidentally break it * without realizing. * * Note for historians. The 1.3 logic would decode to: * "Hello World\u0000Hello World" -- null in the middle --- and 1.4 * unwittingly changed it to current logic. */ @Test public void testDecodeWithInnerPad() { ```
public class Base64 extends BaseNCodec
package org.apache.commons.codec.binary; 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.math.BigInteger; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Random; import org.apache.commons.codec.Charsets; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.EncoderException; import org.apache.commons.lang3.ArrayUtils; import org.junit.Ignore; import org.junit.Test;
public Random getRandom(); @Test public void testIsStringBase64(); @Test public void testBase64(); @Test public void testBase64AtBufferStart(); @Test public void testBase64AtBufferEnd(); @Test public void testBase64AtBufferMiddle(); private void testBase64InBuffer(int startPasSize, int endPadSize); @Test public void testDecodeWithInnerPad(); @Test public void testChunkedEncodeMultipleOf76(); @Test public void testCodec68(); @Test public void testCodeInteger1(); @Test public void testCodeInteger2(); @Test public void testCodeInteger3(); @Test public void testCodeInteger4(); @Test public void testCodeIntegerEdgeCases(); @Test public void testCodeIntegerNull(); @Test public void testConstructors(); @Test public void testConstructor_Int_ByteArray_Boolean(); @Test public void testConstructor_Int_ByteArray_Boolean_UrlSafe(); @Test public void testDecodePadMarkerIndex2(); @Test public void testDecodePadMarkerIndex3(); @Test public void testDecodePadOnly(); @Test public void testDecodePadOnlyChunked(); @Test public void testDecodeWithWhitespace() throws Exception; @Test public void testEmptyBase64(); @Test public void testEncodeDecodeRandom(); @Test public void testEncodeDecodeSmall(); @Test public void testEncodeOverMaxSize() throws Exception; @Test public void testCodec112(); private void testEncodeOverMaxSize(final int maxSize) throws Exception; @Test public void testIgnoringNonBase64InDecode() throws Exception; @Test public void testIsArrayByteBase64(); @Test public void testIsUrlSafe(); @Test public void testKnownDecodings(); @Test public void testKnownEncodings(); @Test public void testNonBase64Test() throws Exception; @Test public void testObjectDecodeWithInvalidParameter() throws Exception; @Test public void testObjectDecodeWithValidParameter() throws Exception; @Test public void testObjectEncodeWithInvalidParameter() throws Exception; @Test public void testObjectEncodeWithValidParameter() throws Exception; @Test public void testObjectEncode() throws Exception; @Test public void testPairs(); @Test public void testRfc2045Section2Dot1CrLfDefinition(); @Test public void testRfc2045Section6Dot8ChunkSizeDefinition(); @Test public void testRfc1421Section6Dot8ChunkSizeDefinition(); @Test public void testRfc4648Section10Decode(); @Test public void testRfc4648Section10DecodeWithCrLf(); @Test public void testRfc4648Section10Encode(); @Test public void testRfc4648Section10DecodeEncode(); private void testDecodeEncode(final String encodedText); @Test public void testRfc4648Section10EncodeDecode(); private void testEncodeDecode(final String plainText); @Test public void testSingletons(); @Test public void testSingletonsChunked(); @Test public void testTriplets(); @Test public void testTripletsChunked(); @Test public void testUrlSafe(); @Test public void testUUID() throws DecoderException; @Test public void testByteToStringVariations() throws DecoderException; @Test public void testStringToByteVariations() throws DecoderException; private String toString(final byte[] data); @Test @Ignore public void testHugeLineSeparator();
0b0ae06d5d6d2ef79e2adc1c4cd60655cf9a3f9ac634e45f30d1c1c6faff2c22
[ "org.apache.commons.codec.binary.Base64Test::testDecodeWithInnerPad" ]
private static final int BITS_PER_ENCODED_BYTE = 6; private static final int BYTES_PER_UNENCODED_BLOCK = 3; private static final int BYTES_PER_ENCODED_BLOCK = 4; static final byte[] CHUNK_SEPARATOR = {'\r', '\n'}; private static final byte[] STANDARD_ENCODE_TABLE = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; private static final byte[] URL_SAFE_ENCODE_TABLE = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_' }; private static final byte[] DECODE_TABLE = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 00-0f -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10-1f -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63, // 20-2f + - / 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, // 30-3f 0-9 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 40-4f A-O 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63, // 50-5f P-Z _ -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // 60-6f a-o 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 // 70-7a p-z }; private static final int MASK_6BITS = 0x3f; private final byte[] encodeTable; private final byte[] decodeTable = DECODE_TABLE; private final byte[] lineSeparator; private final int decodeSize; private final int encodeSize;
@Test public void testDecodeWithInnerPad()
private static final Charset CHARSET_UTF8 = Charsets.UTF_8; private final Random random = new Random();
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.binary; 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.math.BigInteger; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Random; import org.apache.commons.codec.Charsets; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.EncoderException; import org.apache.commons.lang3.ArrayUtils; import org.junit.Ignore; import org.junit.Test; /** * Test cases for Base64 class. * * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a> * @version $Id$ */ public class Base64Test { private static final Charset CHARSET_UTF8 = Charsets.UTF_8; private final Random random = new Random(); /** * @return Returns the random. */ public Random getRandom() { return this.random; } /** * Test the isStringBase64 method. */ @Test public void testIsStringBase64() { final String nullString = null; final String emptyString = ""; final String validString = "abc===defg\n\r123456\r789\r\rABC\n\nDEF==GHI\r\nJKL=============="; final String invalidString = validString + (char) 0; // append null // character try { Base64.isBase64(nullString); fail("Base64.isStringBase64() should not be null-safe."); } catch (final NullPointerException npe) { assertNotNull("Base64.isStringBase64() should not be null-safe.", npe); } assertTrue("Base64.isStringBase64(empty-string) is true", Base64.isBase64(emptyString)); assertTrue("Base64.isStringBase64(valid-string) is true", Base64.isBase64(validString)); assertFalse("Base64.isStringBase64(invalid-string) is false", Base64.isBase64(invalidString)); } /** * Test the Base64 implementation */ @Test public void testBase64() { final String content = "Hello World"; String encodedContent; byte[] encodedBytes = Base64.encodeBase64(StringUtils.getBytesUtf8(content)); encodedContent = StringUtils.newStringUtf8(encodedBytes); assertEquals("encoding hello world", "SGVsbG8gV29ybGQ=", encodedContent); Base64 b64 = new Base64(BaseNCodec.MIME_CHUNK_SIZE, null); // null // lineSeparator // same as // saying // no-chunking encodedBytes = b64.encode(StringUtils.getBytesUtf8(content)); encodedContent = StringUtils.newStringUtf8(encodedBytes); assertEquals("encoding hello world", "SGVsbG8gV29ybGQ=", encodedContent); b64 = new Base64(0, null); // null lineSeparator same as saying // no-chunking encodedBytes = b64.encode(StringUtils.getBytesUtf8(content)); encodedContent = StringUtils.newStringUtf8(encodedBytes); assertEquals("encoding hello world", "SGVsbG8gV29ybGQ=", encodedContent); // bogus characters to decode (to skip actually) {e-acute*6} final byte[] decode = b64.decode("SGVsbG{\u00e9\u00e9\u00e9\u00e9\u00e9\u00e9}8gV29ybGQ="); final String decodeString = StringUtils.newStringUtf8(decode); assertEquals("decode hello world", "Hello World", decodeString); } @Test public void testBase64AtBufferStart() { testBase64InBuffer(0, 100); } @Test public void testBase64AtBufferEnd() { testBase64InBuffer(100, 0); } @Test public void testBase64AtBufferMiddle() { testBase64InBuffer(100, 100); } private void testBase64InBuffer(int startPasSize, int endPadSize) { final String content = "Hello World"; String encodedContent; final byte[] bytesUtf8 = StringUtils.getBytesUtf8(content); byte[] buffer = ArrayUtils.addAll(bytesUtf8, new byte[endPadSize]); buffer = ArrayUtils.addAll(new byte[startPasSize], buffer); byte[] encodedBytes = new Base64().encode(buffer, startPasSize, bytesUtf8.length); encodedContent = StringUtils.newStringUtf8(encodedBytes); assertEquals("encoding hello world", "SGVsbG8gV29ybGQ=", encodedContent); } /** * Test our decode with pad character in the middle. (Our current * implementation: halt decode and return what we've got so far). * * The point of this test is not to say * "this is the correct way to decode base64." The point is simply to keep * us aware of the current logic since 1.4 so we don't accidentally break it * without realizing. * * Note for historians. The 1.3 logic would decode to: * "Hello World\u0000Hello World" -- null in the middle --- and 1.4 * unwittingly changed it to current logic. */ @Test public void testDecodeWithInnerPad() { final String content = "SGVsbG8gV29ybGQ=SGVsbG8gV29ybGQ="; final byte[] result = Base64.decodeBase64(content); final byte[] shouldBe = StringUtils.getBytesUtf8("Hello World"); assertTrue("decode should halt at pad (=)", Arrays.equals(result, shouldBe)); } /** * Tests Base64.encodeBase64(). */ @Test public void testChunkedEncodeMultipleOf76() { final byte[] expectedEncode = Base64.encodeBase64(Base64TestData.DECODED, true); // convert to "\r\n" so we're equal to the old openssl encoding test // stored // in Base64TestData.ENCODED_76_CHARS_PER_LINE: final String actualResult = Base64TestData.ENCODED_76_CHARS_PER_LINE.replaceAll("\n", "\r\n"); final byte[] actualEncode = StringUtils.getBytesUtf8(actualResult); assertTrue("chunkedEncodeMultipleOf76", Arrays.equals(expectedEncode, actualEncode)); } /** * CODEC-68: isBase64 throws ArrayIndexOutOfBoundsException on some * non-BASE64 bytes */ @Test public void testCodec68() { final byte[] x = new byte[] { 'n', 'A', '=', '=', (byte) 0x9c }; Base64.decodeBase64(x); } @Test public void testCodeInteger1() { final String encodedInt1 = "li7dzDacuo67Jg7mtqEm2TRuOMU="; final BigInteger bigInt1 = new BigInteger("85739377120809420210425962799" + "0318636601332086981"); assertEquals(encodedInt1, new String(Base64.encodeInteger(bigInt1))); assertEquals(bigInt1, Base64.decodeInteger(encodedInt1.getBytes(CHARSET_UTF8))); } @Test public void testCodeInteger2() { final String encodedInt2 = "9B5ypLY9pMOmtxCeTDHgwdNFeGs="; final BigInteger bigInt2 = new BigInteger("13936727572861167254666467268" + "91466679477132949611"); assertEquals(encodedInt2, new String(Base64.encodeInteger(bigInt2))); assertEquals(bigInt2, Base64.decodeInteger(encodedInt2.getBytes(CHARSET_UTF8))); } @Test public void testCodeInteger3() { final String encodedInt3 = "FKIhdgaG5LGKiEtF1vHy4f3y700zaD6QwDS3IrNVGzNp2" + "rY+1LFWTK6D44AyiC1n8uWz1itkYMZF0/aKDK0Yjg=="; final BigInteger bigInt3 = new BigInteger( "10806548154093873461951748545" + "1196989136416448805819079363524309897749044958112417136240557" + "4495062430572478766856090958495998158114332651671116876320938126"); assertEquals(encodedInt3, new String(Base64.encodeInteger(bigInt3))); assertEquals(bigInt3, Base64.decodeInteger(encodedInt3.getBytes(CHARSET_UTF8))); } @Test public void testCodeInteger4() { final String encodedInt4 = "ctA8YGxrtngg/zKVvqEOefnwmViFztcnPBYPlJsvh6yKI" + "4iDm68fnp4Mi3RrJ6bZAygFrUIQLxLjV+OJtgJAEto0xAs+Mehuq1DkSFEpP3o" + "DzCTOsrOiS1DwQe4oIb7zVk/9l7aPtJMHW0LVlMdwZNFNNJoqMcT2ZfCPrfvYv" + "Q0="; final BigInteger bigInt4 = new BigInteger( "80624726256040348115552042320" + "6968135001872753709424419772586693950232350200555646471175944" + "519297087885987040810778908507262272892702303774422853675597" + "748008534040890923814202286633163248086055216976551456088015" + "338880713818192088877057717530169381044092839402438015097654" + "53542091716518238707344493641683483917"); assertEquals(encodedInt4, new String(Base64.encodeInteger(bigInt4))); assertEquals(bigInt4, Base64.decodeInteger(encodedInt4.getBytes(CHARSET_UTF8))); } @Test public void testCodeIntegerEdgeCases() { // TODO } @Test public void testCodeIntegerNull() { try { Base64.encodeInteger(null); fail("Exception not thrown when passing in null to encodeInteger(BigInteger)"); } catch (final NullPointerException npe) { // expected } catch (final Exception e) { fail("Incorrect Exception caught when passing in null to encodeInteger(BigInteger)"); } } @Test public void testConstructors() { Base64 base64; base64 = new Base64(); base64 = new Base64(-1); base64 = new Base64(-1, new byte[] {}); base64 = new Base64(64, new byte[] {}); try { base64 = new Base64(-1, new byte[] { 'A' }); // TODO do we need to // check sep if len // = -1? fail("Should have rejected attempt to use 'A' as a line separator"); } catch (final IllegalArgumentException ignored) { // Expected } try { base64 = new Base64(64, new byte[] { 'A' }); fail("Should have rejected attempt to use 'A' as a line separator"); } catch (final IllegalArgumentException ignored) { // Expected } try { base64 = new Base64(64, new byte[] { '=' }); fail("Should have rejected attempt to use '=' as a line separator"); } catch (final IllegalArgumentException ignored) { // Expected } base64 = new Base64(64, new byte[] { '$' }); // OK try { base64 = new Base64(64, new byte[] { 'A', '$' }); fail("Should have rejected attempt to use 'A$' as a line separator"); } catch (final IllegalArgumentException ignored) { // Expected } base64 = new Base64(64, new byte[] { ' ', '$', '\n', '\r', '\t' }); // OK assertNotNull(base64); } @Test public void testConstructor_Int_ByteArray_Boolean() { final Base64 base64 = new Base64(65, new byte[] { '\t' }, false); final byte[] encoded = base64.encode(Base64TestData.DECODED); String expectedResult = Base64TestData.ENCODED_64_CHARS_PER_LINE; expectedResult = expectedResult.replace('\n', '\t'); final String result = StringUtils.newStringUtf8(encoded); assertEquals("new Base64(65, \\t, false)", expectedResult, result); } @Test public void testConstructor_Int_ByteArray_Boolean_UrlSafe() { // url-safe variation final Base64 base64 = new Base64(64, new byte[] { '\t' }, true); final byte[] encoded = base64.encode(Base64TestData.DECODED); String expectedResult = Base64TestData.ENCODED_64_CHARS_PER_LINE; expectedResult = expectedResult.replaceAll("=", ""); // url-safe has no // == padding. expectedResult = expectedResult.replace('\n', '\t'); expectedResult = expectedResult.replace('+', '-'); expectedResult = expectedResult.replace('/', '_'); final String result = StringUtils.newStringUtf8(encoded); assertEquals("new Base64(64, \\t, true)", result, expectedResult); } /** * Tests conditional true branch for "marker0" test. */ @Test public void testDecodePadMarkerIndex2() { assertEquals("A", new String(Base64.decodeBase64("QQ==".getBytes(CHARSET_UTF8)))); } /** * Tests conditional branches for "marker1" test. */ @Test public void testDecodePadMarkerIndex3() { assertEquals("AA", new String(Base64.decodeBase64("QUE=".getBytes(CHARSET_UTF8)))); assertEquals("AAA", new String(Base64.decodeBase64("QUFB".getBytes(CHARSET_UTF8)))); } @Test public void testDecodePadOnly() { assertEquals(0, Base64.decodeBase64("====".getBytes(CHARSET_UTF8)).length); assertEquals("", new String(Base64.decodeBase64("====".getBytes(CHARSET_UTF8)))); // Test truncated padding assertEquals(0, Base64.decodeBase64("===".getBytes(CHARSET_UTF8)).length); assertEquals(0, Base64.decodeBase64("==".getBytes(CHARSET_UTF8)).length); assertEquals(0, Base64.decodeBase64("=".getBytes(CHARSET_UTF8)).length); assertEquals(0, Base64.decodeBase64("".getBytes(CHARSET_UTF8)).length); } @Test public void testDecodePadOnlyChunked() { assertEquals(0, Base64.decodeBase64("====\n".getBytes(CHARSET_UTF8)).length); assertEquals("", new String(Base64.decodeBase64("====\n".getBytes(CHARSET_UTF8)))); // Test truncated padding assertEquals(0, Base64.decodeBase64("===\n".getBytes(CHARSET_UTF8)).length); assertEquals(0, Base64.decodeBase64("==\n".getBytes(CHARSET_UTF8)).length); assertEquals(0, Base64.decodeBase64("=\n".getBytes(CHARSET_UTF8)).length); assertEquals(0, Base64.decodeBase64("\n".getBytes(CHARSET_UTF8)).length); } @Test public void testDecodeWithWhitespace() throws Exception { final String orig = "I am a late night coder."; final byte[] encodedArray = Base64.encodeBase64(orig.getBytes(CHARSET_UTF8)); final StringBuilder intermediate = new StringBuilder(new String(encodedArray)); intermediate.insert(2, ' '); intermediate.insert(5, '\t'); intermediate.insert(10, '\r'); intermediate.insert(15, '\n'); final byte[] encodedWithWS = intermediate.toString().getBytes(CHARSET_UTF8); final byte[] decodedWithWS = Base64.decodeBase64(encodedWithWS); final String dest = new String(decodedWithWS); assertEquals("Dest string doesn't equal the original", orig, dest); } /** * Test encode and decode of empty byte array. */ @Test public void testEmptyBase64() { byte[] empty = new byte[0]; byte[] result = Base64.encodeBase64(empty); assertEquals("empty base64 encode", 0, result.length); assertEquals("empty base64 encode", null, Base64.encodeBase64(null)); empty = new byte[0]; result = Base64.decodeBase64(empty); assertEquals("empty base64 decode", 0, result.length); assertEquals("empty base64 encode", null, Base64.decodeBase64((byte[]) null)); } // encode/decode a large random array @Test public void testEncodeDecodeRandom() { for (int i = 1; i < 5; i++) { final byte[] data = new byte[this.getRandom().nextInt(10000) + 1]; this.getRandom().nextBytes(data); final byte[] enc = Base64.encodeBase64(data); assertTrue(Base64.isBase64(enc)); final byte[] data2 = Base64.decodeBase64(enc); assertTrue(Arrays.equals(data, data2)); } } // encode/decode random arrays from size 0 to size 11 @Test public void testEncodeDecodeSmall() { for (int i = 0; i < 12; i++) { final byte[] data = new byte[i]; this.getRandom().nextBytes(data); final byte[] enc = Base64.encodeBase64(data); assertTrue("\"" + new String(enc) + "\" is Base64 data.", Base64.isBase64(enc)); final byte[] data2 = Base64.decodeBase64(enc); assertTrue(toString(data) + " equals " + toString(data2), Arrays.equals(data, data2)); } } @Test public void testEncodeOverMaxSize() throws Exception { testEncodeOverMaxSize(-1); testEncodeOverMaxSize(0); testEncodeOverMaxSize(1); testEncodeOverMaxSize(2); } @Test public void testCodec112() { // size calculation assumes always chunked final byte[] in = new byte[] { 0 }; final byte[] out = Base64.encodeBase64(in); Base64.encodeBase64(in, false, false, out.length); } private void testEncodeOverMaxSize(final int maxSize) throws Exception { try { Base64.encodeBase64(Base64TestData.DECODED, true, false, maxSize); fail("Expected " + IllegalArgumentException.class.getName()); } catch (final IllegalArgumentException e) { // Expected } } @Test public void testIgnoringNonBase64InDecode() throws Exception { assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64.decodeBase64( "VGhlIH@$#$@%F1aWN@#@#@@rIGJyb3duIGZve\n\r\t%#%#%#%CBqd##$#$W1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==" .getBytes(CHARSET_UTF8)))); } @Test public void testIsArrayByteBase64() { assertFalse(Base64.isBase64(new byte[] { Byte.MIN_VALUE })); assertFalse(Base64.isBase64(new byte[] { -125 })); assertFalse(Base64.isBase64(new byte[] { -10 })); assertFalse(Base64.isBase64(new byte[] { 0 })); assertFalse(Base64.isBase64(new byte[] { 64, Byte.MAX_VALUE })); assertFalse(Base64.isBase64(new byte[] { Byte.MAX_VALUE })); assertTrue(Base64.isBase64(new byte[] { 'A' })); assertFalse(Base64.isBase64(new byte[] { 'A', Byte.MIN_VALUE })); assertTrue(Base64.isBase64(new byte[] { 'A', 'Z', 'a' })); assertTrue(Base64.isBase64(new byte[] { '/', '=', '+' })); assertFalse(Base64.isBase64(new byte[] { '$' })); } /** * Tests isUrlSafe. */ @Test public void testIsUrlSafe() { final Base64 base64Standard = new Base64(false); final Base64 base64URLSafe = new Base64(true); assertFalse("Base64.isUrlSafe=false", base64Standard.isUrlSafe()); assertTrue("Base64.isUrlSafe=true", base64URLSafe.isUrlSafe()); final byte[] whiteSpace = { ' ', '\n', '\r', '\t' }; assertTrue("Base64.isBase64(whiteSpace)=true", Base64.isBase64(whiteSpace)); } @Test public void testKnownDecodings() { assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64.decodeBase64( "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes(CHARSET_UTF8)))); assertEquals("It was the best of times, it was the worst of times.", new String(Base64.decodeBase64( "SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==".getBytes(CHARSET_UTF8)))); assertEquals("http://jakarta.apache.org/commmons", new String( Base64.decodeBase64("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==".getBytes(CHARSET_UTF8)))); assertEquals("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz", new String(Base64.decodeBase64( "QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==".getBytes(CHARSET_UTF8)))); assertEquals("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", new String(Base64.decodeBase64("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=".getBytes(CHARSET_UTF8)))); assertEquals("xyzzy!", new String(Base64.decodeBase64("eHl6enkh".getBytes(CHARSET_UTF8)))); } @Test public void testKnownEncodings() { assertEquals("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==", new String( Base64.encodeBase64("The quick brown fox jumped over the lazy dogs.".getBytes(CHARSET_UTF8)))); assertEquals( "YmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJs\r\nYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFo\r\nIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBi\r\nbGFoIGJsYWg=\r\n", new String(Base64.encodeBase64Chunked( "blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah" .getBytes(CHARSET_UTF8)))); assertEquals("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==", new String( Base64.encodeBase64("It was the best of times, it was the worst of times.".getBytes(CHARSET_UTF8)))); assertEquals("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==", new String(Base64.encodeBase64("http://jakarta.apache.org/commmons".getBytes(CHARSET_UTF8)))); assertEquals("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==", new String( Base64.encodeBase64("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz".getBytes(CHARSET_UTF8)))); assertEquals("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=", new String(Base64.encodeBase64("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }".getBytes(CHARSET_UTF8)))); assertEquals("eHl6enkh", new String(Base64.encodeBase64("xyzzy!".getBytes(CHARSET_UTF8)))); } @Test public void testNonBase64Test() throws Exception { final byte[] bArray = { '%' }; assertFalse("Invalid Base64 array was incorrectly validated as " + "an array of Base64 encoded data", Base64.isBase64(bArray)); try { final Base64 b64 = new Base64(); final byte[] result = b64.decode(bArray); assertEquals("The result should be empty as the test encoded content did " + "not contain any valid base 64 characters", 0, result.length); } catch (final Exception e) { fail("Exception was thrown when trying to decode " + "invalid base64 encoded data - RFC 2045 requires that all " + "non base64 character be discarded, an exception should not" + " have been thrown"); } } @Test public void testObjectDecodeWithInvalidParameter() throws Exception { final Base64 b64 = new Base64(); try { b64.decode(Integer.valueOf(5)); fail("decode(Object) didn't throw an exception when passed an Integer object"); } catch (final DecoderException e) { // ignored } } @Test public void testObjectDecodeWithValidParameter() throws Exception { final String original = "Hello World!"; final Object o = Base64.encodeBase64(original.getBytes(CHARSET_UTF8)); final Base64 b64 = new Base64(); final Object oDecoded = b64.decode(o); final byte[] baDecoded = (byte[]) oDecoded; final String dest = new String(baDecoded); assertEquals("dest string does not equal original", original, dest); } @Test public void testObjectEncodeWithInvalidParameter() throws Exception { final Base64 b64 = new Base64(); try { b64.encode("Yadayadayada"); fail("encode(Object) didn't throw an exception when passed a String object"); } catch (final EncoderException e) { // Expected } } @Test public void testObjectEncodeWithValidParameter() throws Exception { final String original = "Hello World!"; final Object origObj = original.getBytes(CHARSET_UTF8); final Base64 b64 = new Base64(); final Object oEncoded = b64.encode(origObj); final byte[] bArray = Base64.decodeBase64((byte[]) oEncoded); final String dest = new String(bArray); assertEquals("dest string does not equal original", original, dest); } @Test public void testObjectEncode() throws Exception { final Base64 b64 = new Base64(); assertEquals("SGVsbG8gV29ybGQ=", new String(b64.encode("Hello World".getBytes(CHARSET_UTF8)))); } @Test public void testPairs() { assertEquals("AAA=", new String(Base64.encodeBase64(new byte[] { 0, 0 }))); for (int i = -128; i <= 127; i++) { final byte test[] = { (byte) i, (byte) i }; assertTrue(Arrays.equals(test, Base64.decodeBase64(Base64.encodeBase64(test)))); } } /** * Tests RFC 2045 section 2.1 CRLF definition. */ @Test public void testRfc2045Section2Dot1CrLfDefinition() { assertTrue(Arrays.equals(new byte[] { 13, 10 }, Base64.CHUNK_SEPARATOR)); } /** * Tests RFC 2045 section 6.8 chuck size definition. */ @Test public void testRfc2045Section6Dot8ChunkSizeDefinition() { assertEquals(76, BaseNCodec.MIME_CHUNK_SIZE); } /** * Tests RFC 1421 section 4.3.2.4 chuck size definition. */ @Test public void testRfc1421Section6Dot8ChunkSizeDefinition() { assertEquals(64, BaseNCodec.PEM_CHUNK_SIZE); } /** * Tests RFC 4648 section 10 test vectors. * <ul> * <li>BASE64("") = ""</li> * <li>BASE64("f") = "Zg=="</li> * <li>BASE64("fo") = "Zm8="</li> * <li>BASE64("foo") = "Zm9v"</li> * <li>BASE64("foob") = "Zm9vYg=="</li> * <li>BASE64("fooba") = "Zm9vYmE="</li> * <li>BASE64("foobar") = "Zm9vYmFy"</li> * </ul> * * @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/ * html/rfc4648</a> */ @Test public void testRfc4648Section10Decode() { assertEquals("", StringUtils.newStringUsAscii(Base64.decodeBase64(""))); assertEquals("f", StringUtils.newStringUsAscii(Base64.decodeBase64("Zg=="))); assertEquals("fo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm8="))); assertEquals("foo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9v"))); assertEquals("foob", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYg=="))); assertEquals("fooba", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmE="))); assertEquals("foobar", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmFy"))); } /** * Tests RFC 4648 section 10 test vectors. * <ul> * <li>BASE64("") = ""</li> * <li>BASE64("f") = "Zg=="</li> * <li>BASE64("fo") = "Zm8="</li> * <li>BASE64("foo") = "Zm9v"</li> * <li>BASE64("foob") = "Zm9vYg=="</li> * <li>BASE64("fooba") = "Zm9vYmE="</li> * <li>BASE64("foobar") = "Zm9vYmFy"</li> * </ul> * * @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/ * html/rfc4648</a> */ @Test public void testRfc4648Section10DecodeWithCrLf() { final String CRLF = StringUtils.newStringUsAscii(Base64.CHUNK_SEPARATOR); assertEquals("", StringUtils.newStringUsAscii(Base64.decodeBase64("" + CRLF))); assertEquals("f", StringUtils.newStringUsAscii(Base64.decodeBase64("Zg==" + CRLF))); assertEquals("fo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm8=" + CRLF))); assertEquals("foo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9v" + CRLF))); assertEquals("foob", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYg==" + CRLF))); assertEquals("fooba", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmE=" + CRLF))); assertEquals("foobar", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmFy" + CRLF))); } /** * Tests RFC 4648 section 10 test vectors. * <ul> * <li>BASE64("") = ""</li> * <li>BASE64("f") = "Zg=="</li> * <li>BASE64("fo") = "Zm8="</li> * <li>BASE64("foo") = "Zm9v"</li> * <li>BASE64("foob") = "Zm9vYg=="</li> * <li>BASE64("fooba") = "Zm9vYmE="</li> * <li>BASE64("foobar") = "Zm9vYmFy"</li> * </ul> * * @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/ * html/rfc4648</a> */ @Test public void testRfc4648Section10Encode() { assertEquals("", Base64.encodeBase64String(StringUtils.getBytesUtf8(""))); assertEquals("Zg==", Base64.encodeBase64String(StringUtils.getBytesUtf8("f"))); assertEquals("Zm8=", Base64.encodeBase64String(StringUtils.getBytesUtf8("fo"))); assertEquals("Zm9v", Base64.encodeBase64String(StringUtils.getBytesUtf8("foo"))); assertEquals("Zm9vYg==", Base64.encodeBase64String(StringUtils.getBytesUtf8("foob"))); assertEquals("Zm9vYmE=", Base64.encodeBase64String(StringUtils.getBytesUtf8("fooba"))); assertEquals("Zm9vYmFy", Base64.encodeBase64String(StringUtils.getBytesUtf8("foobar"))); } /** * Tests RFC 4648 section 10 test vectors. * <ul> * <li>BASE64("") = ""</li> * <li>BASE64("f") = "Zg=="</li> * <li>BASE64("fo") = "Zm8="</li> * <li>BASE64("foo") = "Zm9v"</li> * <li>BASE64("foob") = "Zm9vYg=="</li> * <li>BASE64("fooba") = "Zm9vYmE="</li> * <li>BASE64("foobar") = "Zm9vYmFy"</li> * </ul> * * @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/ * html/rfc4648</a> */ @Test public void testRfc4648Section10DecodeEncode() { testDecodeEncode(""); testDecodeEncode("Zg=="); testDecodeEncode("Zm8="); testDecodeEncode("Zm9v"); testDecodeEncode("Zm9vYg=="); testDecodeEncode("Zm9vYmE="); testDecodeEncode("Zm9vYmFy"); } private void testDecodeEncode(final String encodedText) { final String decodedText = StringUtils.newStringUsAscii(Base64.decodeBase64(encodedText)); final String encodedText2 = Base64.encodeBase64String(StringUtils.getBytesUtf8(decodedText)); assertEquals(encodedText, encodedText2); } /** * Tests RFC 4648 section 10 test vectors. * <ul> * <li>BASE64("") = ""</li> * <li>BASE64("f") = "Zg=="</li> * <li>BASE64("fo") = "Zm8="</li> * <li>BASE64("foo") = "Zm9v"</li> * <li>BASE64("foob") = "Zm9vYg=="</li> * <li>BASE64("fooba") = "Zm9vYmE="</li> * <li>BASE64("foobar") = "Zm9vYmFy"</li> * </ul> * * @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/ * html/rfc4648</a> */ @Test public void testRfc4648Section10EncodeDecode() { testEncodeDecode(""); testEncodeDecode("f"); testEncodeDecode("fo"); testEncodeDecode("foo"); testEncodeDecode("foob"); testEncodeDecode("fooba"); testEncodeDecode("foobar"); } private void testEncodeDecode(final String plainText) { final String encodedText = Base64.encodeBase64String(StringUtils.getBytesUtf8(plainText)); final String decodedText = StringUtils.newStringUsAscii(Base64.decodeBase64(encodedText)); assertEquals(plainText, decodedText); } @Test public void testSingletons() { assertEquals("AA==", new String(Base64.encodeBase64(new byte[] { (byte) 0 }))); assertEquals("AQ==", new String(Base64.encodeBase64(new byte[] { (byte) 1 }))); assertEquals("Ag==", new String(Base64.encodeBase64(new byte[] { (byte) 2 }))); assertEquals("Aw==", new String(Base64.encodeBase64(new byte[] { (byte) 3 }))); assertEquals("BA==", new String(Base64.encodeBase64(new byte[] { (byte) 4 }))); assertEquals("BQ==", new String(Base64.encodeBase64(new byte[] { (byte) 5 }))); assertEquals("Bg==", new String(Base64.encodeBase64(new byte[] { (byte) 6 }))); assertEquals("Bw==", new String(Base64.encodeBase64(new byte[] { (byte) 7 }))); assertEquals("CA==", new String(Base64.encodeBase64(new byte[] { (byte) 8 }))); assertEquals("CQ==", new String(Base64.encodeBase64(new byte[] { (byte) 9 }))); assertEquals("Cg==", new String(Base64.encodeBase64(new byte[] { (byte) 10 }))); assertEquals("Cw==", new String(Base64.encodeBase64(new byte[] { (byte) 11 }))); assertEquals("DA==", new String(Base64.encodeBase64(new byte[] { (byte) 12 }))); assertEquals("DQ==", new String(Base64.encodeBase64(new byte[] { (byte) 13 }))); assertEquals("Dg==", new String(Base64.encodeBase64(new byte[] { (byte) 14 }))); assertEquals("Dw==", new String(Base64.encodeBase64(new byte[] { (byte) 15 }))); assertEquals("EA==", new String(Base64.encodeBase64(new byte[] { (byte) 16 }))); assertEquals("EQ==", new String(Base64.encodeBase64(new byte[] { (byte) 17 }))); assertEquals("Eg==", new String(Base64.encodeBase64(new byte[] { (byte) 18 }))); assertEquals("Ew==", new String(Base64.encodeBase64(new byte[] { (byte) 19 }))); assertEquals("FA==", new String(Base64.encodeBase64(new byte[] { (byte) 20 }))); assertEquals("FQ==", new String(Base64.encodeBase64(new byte[] { (byte) 21 }))); assertEquals("Fg==", new String(Base64.encodeBase64(new byte[] { (byte) 22 }))); assertEquals("Fw==", new String(Base64.encodeBase64(new byte[] { (byte) 23 }))); assertEquals("GA==", new String(Base64.encodeBase64(new byte[] { (byte) 24 }))); assertEquals("GQ==", new String(Base64.encodeBase64(new byte[] { (byte) 25 }))); assertEquals("Gg==", new String(Base64.encodeBase64(new byte[] { (byte) 26 }))); assertEquals("Gw==", new String(Base64.encodeBase64(new byte[] { (byte) 27 }))); assertEquals("HA==", new String(Base64.encodeBase64(new byte[] { (byte) 28 }))); assertEquals("HQ==", new String(Base64.encodeBase64(new byte[] { (byte) 29 }))); assertEquals("Hg==", new String(Base64.encodeBase64(new byte[] { (byte) 30 }))); assertEquals("Hw==", new String(Base64.encodeBase64(new byte[] { (byte) 31 }))); assertEquals("IA==", new String(Base64.encodeBase64(new byte[] { (byte) 32 }))); assertEquals("IQ==", new String(Base64.encodeBase64(new byte[] { (byte) 33 }))); assertEquals("Ig==", new String(Base64.encodeBase64(new byte[] { (byte) 34 }))); assertEquals("Iw==", new String(Base64.encodeBase64(new byte[] { (byte) 35 }))); assertEquals("JA==", new String(Base64.encodeBase64(new byte[] { (byte) 36 }))); assertEquals("JQ==", new String(Base64.encodeBase64(new byte[] { (byte) 37 }))); assertEquals("Jg==", new String(Base64.encodeBase64(new byte[] { (byte) 38 }))); assertEquals("Jw==", new String(Base64.encodeBase64(new byte[] { (byte) 39 }))); assertEquals("KA==", new String(Base64.encodeBase64(new byte[] { (byte) 40 }))); assertEquals("KQ==", new String(Base64.encodeBase64(new byte[] { (byte) 41 }))); assertEquals("Kg==", new String(Base64.encodeBase64(new byte[] { (byte) 42 }))); assertEquals("Kw==", new String(Base64.encodeBase64(new byte[] { (byte) 43 }))); assertEquals("LA==", new String(Base64.encodeBase64(new byte[] { (byte) 44 }))); assertEquals("LQ==", new String(Base64.encodeBase64(new byte[] { (byte) 45 }))); assertEquals("Lg==", new String(Base64.encodeBase64(new byte[] { (byte) 46 }))); assertEquals("Lw==", new String(Base64.encodeBase64(new byte[] { (byte) 47 }))); assertEquals("MA==", new String(Base64.encodeBase64(new byte[] { (byte) 48 }))); assertEquals("MQ==", new String(Base64.encodeBase64(new byte[] { (byte) 49 }))); assertEquals("Mg==", new String(Base64.encodeBase64(new byte[] { (byte) 50 }))); assertEquals("Mw==", new String(Base64.encodeBase64(new byte[] { (byte) 51 }))); assertEquals("NA==", new String(Base64.encodeBase64(new byte[] { (byte) 52 }))); assertEquals("NQ==", new String(Base64.encodeBase64(new byte[] { (byte) 53 }))); assertEquals("Ng==", new String(Base64.encodeBase64(new byte[] { (byte) 54 }))); assertEquals("Nw==", new String(Base64.encodeBase64(new byte[] { (byte) 55 }))); assertEquals("OA==", new String(Base64.encodeBase64(new byte[] { (byte) 56 }))); assertEquals("OQ==", new String(Base64.encodeBase64(new byte[] { (byte) 57 }))); assertEquals("Og==", new String(Base64.encodeBase64(new byte[] { (byte) 58 }))); assertEquals("Ow==", new String(Base64.encodeBase64(new byte[] { (byte) 59 }))); assertEquals("PA==", new String(Base64.encodeBase64(new byte[] { (byte) 60 }))); assertEquals("PQ==", new String(Base64.encodeBase64(new byte[] { (byte) 61 }))); assertEquals("Pg==", new String(Base64.encodeBase64(new byte[] { (byte) 62 }))); assertEquals("Pw==", new String(Base64.encodeBase64(new byte[] { (byte) 63 }))); assertEquals("QA==", new String(Base64.encodeBase64(new byte[] { (byte) 64 }))); assertEquals("QQ==", new String(Base64.encodeBase64(new byte[] { (byte) 65 }))); assertEquals("Qg==", new String(Base64.encodeBase64(new byte[] { (byte) 66 }))); assertEquals("Qw==", new String(Base64.encodeBase64(new byte[] { (byte) 67 }))); assertEquals("RA==", new String(Base64.encodeBase64(new byte[] { (byte) 68 }))); assertEquals("RQ==", new String(Base64.encodeBase64(new byte[] { (byte) 69 }))); assertEquals("Rg==", new String(Base64.encodeBase64(new byte[] { (byte) 70 }))); assertEquals("Rw==", new String(Base64.encodeBase64(new byte[] { (byte) 71 }))); assertEquals("SA==", new String(Base64.encodeBase64(new byte[] { (byte) 72 }))); assertEquals("SQ==", new String(Base64.encodeBase64(new byte[] { (byte) 73 }))); assertEquals("Sg==", new String(Base64.encodeBase64(new byte[] { (byte) 74 }))); assertEquals("Sw==", new String(Base64.encodeBase64(new byte[] { (byte) 75 }))); assertEquals("TA==", new String(Base64.encodeBase64(new byte[] { (byte) 76 }))); assertEquals("TQ==", new String(Base64.encodeBase64(new byte[] { (byte) 77 }))); assertEquals("Tg==", new String(Base64.encodeBase64(new byte[] { (byte) 78 }))); assertEquals("Tw==", new String(Base64.encodeBase64(new byte[] { (byte) 79 }))); assertEquals("UA==", new String(Base64.encodeBase64(new byte[] { (byte) 80 }))); assertEquals("UQ==", new String(Base64.encodeBase64(new byte[] { (byte) 81 }))); assertEquals("Ug==", new String(Base64.encodeBase64(new byte[] { (byte) 82 }))); assertEquals("Uw==", new String(Base64.encodeBase64(new byte[] { (byte) 83 }))); assertEquals("VA==", new String(Base64.encodeBase64(new byte[] { (byte) 84 }))); assertEquals("VQ==", new String(Base64.encodeBase64(new byte[] { (byte) 85 }))); assertEquals("Vg==", new String(Base64.encodeBase64(new byte[] { (byte) 86 }))); assertEquals("Vw==", new String(Base64.encodeBase64(new byte[] { (byte) 87 }))); assertEquals("WA==", new String(Base64.encodeBase64(new byte[] { (byte) 88 }))); assertEquals("WQ==", new String(Base64.encodeBase64(new byte[] { (byte) 89 }))); assertEquals("Wg==", new String(Base64.encodeBase64(new byte[] { (byte) 90 }))); assertEquals("Ww==", new String(Base64.encodeBase64(new byte[] { (byte) 91 }))); assertEquals("XA==", new String(Base64.encodeBase64(new byte[] { (byte) 92 }))); assertEquals("XQ==", new String(Base64.encodeBase64(new byte[] { (byte) 93 }))); assertEquals("Xg==", new String(Base64.encodeBase64(new byte[] { (byte) 94 }))); assertEquals("Xw==", new String(Base64.encodeBase64(new byte[] { (byte) 95 }))); assertEquals("YA==", new String(Base64.encodeBase64(new byte[] { (byte) 96 }))); assertEquals("YQ==", new String(Base64.encodeBase64(new byte[] { (byte) 97 }))); assertEquals("Yg==", new String(Base64.encodeBase64(new byte[] { (byte) 98 }))); assertEquals("Yw==", new String(Base64.encodeBase64(new byte[] { (byte) 99 }))); assertEquals("ZA==", new String(Base64.encodeBase64(new byte[] { (byte) 100 }))); assertEquals("ZQ==", new String(Base64.encodeBase64(new byte[] { (byte) 101 }))); assertEquals("Zg==", new String(Base64.encodeBase64(new byte[] { (byte) 102 }))); assertEquals("Zw==", new String(Base64.encodeBase64(new byte[] { (byte) 103 }))); assertEquals("aA==", new String(Base64.encodeBase64(new byte[] { (byte) 104 }))); for (int i = -128; i <= 127; i++) { final byte test[] = { (byte) i }; assertTrue(Arrays.equals(test, Base64.decodeBase64(Base64.encodeBase64(test)))); } } @Test public void testSingletonsChunked() { assertEquals("AA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0 }))); assertEquals("AQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 1 }))); assertEquals("Ag==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 2 }))); assertEquals("Aw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 3 }))); assertEquals("BA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 4 }))); assertEquals("BQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 5 }))); assertEquals("Bg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 6 }))); assertEquals("Bw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 7 }))); assertEquals("CA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 8 }))); assertEquals("CQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 9 }))); assertEquals("Cg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 10 }))); assertEquals("Cw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 11 }))); assertEquals("DA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 12 }))); assertEquals("DQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 13 }))); assertEquals("Dg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 14 }))); assertEquals("Dw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 15 }))); assertEquals("EA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 16 }))); assertEquals("EQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 17 }))); assertEquals("Eg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 18 }))); assertEquals("Ew==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 19 }))); assertEquals("FA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 20 }))); assertEquals("FQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 21 }))); assertEquals("Fg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 22 }))); assertEquals("Fw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 23 }))); assertEquals("GA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 24 }))); assertEquals("GQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 25 }))); assertEquals("Gg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 26 }))); assertEquals("Gw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 27 }))); assertEquals("HA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 28 }))); assertEquals("HQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 29 }))); assertEquals("Hg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 30 }))); assertEquals("Hw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 31 }))); assertEquals("IA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 32 }))); assertEquals("IQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 33 }))); assertEquals("Ig==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 34 }))); assertEquals("Iw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 35 }))); assertEquals("JA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 36 }))); assertEquals("JQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 37 }))); assertEquals("Jg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 38 }))); assertEquals("Jw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 39 }))); assertEquals("KA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 40 }))); assertEquals("KQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 41 }))); assertEquals("Kg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 42 }))); assertEquals("Kw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 43 }))); assertEquals("LA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 44 }))); assertEquals("LQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 45 }))); assertEquals("Lg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 46 }))); assertEquals("Lw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 47 }))); assertEquals("MA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 48 }))); assertEquals("MQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 49 }))); assertEquals("Mg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 50 }))); assertEquals("Mw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 51 }))); assertEquals("NA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 52 }))); assertEquals("NQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 53 }))); assertEquals("Ng==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 54 }))); assertEquals("Nw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 55 }))); assertEquals("OA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 56 }))); assertEquals("OQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 57 }))); assertEquals("Og==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 58 }))); assertEquals("Ow==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 59 }))); assertEquals("PA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 60 }))); assertEquals("PQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 61 }))); assertEquals("Pg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 62 }))); assertEquals("Pw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 63 }))); assertEquals("QA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 64 }))); assertEquals("QQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 65 }))); assertEquals("Qg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 66 }))); assertEquals("Qw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 67 }))); assertEquals("RA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 68 }))); assertEquals("RQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 69 }))); assertEquals("Rg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 70 }))); assertEquals("Rw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 71 }))); assertEquals("SA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 72 }))); assertEquals("SQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 73 }))); assertEquals("Sg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 74 }))); assertEquals("Sw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 75 }))); assertEquals("TA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 76 }))); assertEquals("TQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 77 }))); assertEquals("Tg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 78 }))); assertEquals("Tw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 79 }))); assertEquals("UA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 80 }))); assertEquals("UQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 81 }))); assertEquals("Ug==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 82 }))); assertEquals("Uw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 83 }))); assertEquals("VA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 84 }))); assertEquals("VQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 85 }))); assertEquals("Vg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 86 }))); assertEquals("Vw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 87 }))); assertEquals("WA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 88 }))); assertEquals("WQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 89 }))); assertEquals("Wg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 90 }))); assertEquals("Ww==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 91 }))); assertEquals("XA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 92 }))); assertEquals("XQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 93 }))); assertEquals("Xg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 94 }))); assertEquals("Xw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 95 }))); assertEquals("YA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 96 }))); assertEquals("YQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 97 }))); assertEquals("Yg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 98 }))); assertEquals("Yw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 99 }))); assertEquals("ZA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 100 }))); assertEquals("ZQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 101 }))); assertEquals("Zg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 102 }))); assertEquals("Zw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 103 }))); assertEquals("aA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 104 }))); } @Test public void testTriplets() { assertEquals("AAAA", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 0 }))); assertEquals("AAAB", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 1 }))); assertEquals("AAAC", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 2 }))); assertEquals("AAAD", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 3 }))); assertEquals("AAAE", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 4 }))); assertEquals("AAAF", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 5 }))); assertEquals("AAAG", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 6 }))); assertEquals("AAAH", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 7 }))); assertEquals("AAAI", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 8 }))); assertEquals("AAAJ", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 9 }))); assertEquals("AAAK", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 10 }))); assertEquals("AAAL", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 11 }))); assertEquals("AAAM", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 12 }))); assertEquals("AAAN", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 13 }))); assertEquals("AAAO", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 14 }))); assertEquals("AAAP", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 15 }))); assertEquals("AAAQ", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 16 }))); assertEquals("AAAR", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 17 }))); assertEquals("AAAS", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 18 }))); assertEquals("AAAT", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 19 }))); assertEquals("AAAU", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 20 }))); assertEquals("AAAV", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 21 }))); assertEquals("AAAW", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 22 }))); assertEquals("AAAX", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 23 }))); assertEquals("AAAY", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 24 }))); assertEquals("AAAZ", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 25 }))); assertEquals("AAAa", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 26 }))); assertEquals("AAAb", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 27 }))); assertEquals("AAAc", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 28 }))); assertEquals("AAAd", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 29 }))); assertEquals("AAAe", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 30 }))); assertEquals("AAAf", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 31 }))); assertEquals("AAAg", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 32 }))); assertEquals("AAAh", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 33 }))); assertEquals("AAAi", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 34 }))); assertEquals("AAAj", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 35 }))); assertEquals("AAAk", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 36 }))); assertEquals("AAAl", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 37 }))); assertEquals("AAAm", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 38 }))); assertEquals("AAAn", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 39 }))); assertEquals("AAAo", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 40 }))); assertEquals("AAAp", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 41 }))); assertEquals("AAAq", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 42 }))); assertEquals("AAAr", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 43 }))); assertEquals("AAAs", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 44 }))); assertEquals("AAAt", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 45 }))); assertEquals("AAAu", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 46 }))); assertEquals("AAAv", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 47 }))); assertEquals("AAAw", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 48 }))); assertEquals("AAAx", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 49 }))); assertEquals("AAAy", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 50 }))); assertEquals("AAAz", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 51 }))); assertEquals("AAA0", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 52 }))); assertEquals("AAA1", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 53 }))); assertEquals("AAA2", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 54 }))); assertEquals("AAA3", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 55 }))); assertEquals("AAA4", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 56 }))); assertEquals("AAA5", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 57 }))); assertEquals("AAA6", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 58 }))); assertEquals("AAA7", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 59 }))); assertEquals("AAA8", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 60 }))); assertEquals("AAA9", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 61 }))); assertEquals("AAA+", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 62 }))); assertEquals("AAA/", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 63 }))); } @Test public void testTripletsChunked() { assertEquals("AAAA\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 0 }))); assertEquals("AAAB\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 1 }))); assertEquals("AAAC\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 2 }))); assertEquals("AAAD\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 3 }))); assertEquals("AAAE\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 4 }))); assertEquals("AAAF\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 5 }))); assertEquals("AAAG\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 6 }))); assertEquals("AAAH\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 7 }))); assertEquals("AAAI\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 8 }))); assertEquals("AAAJ\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 9 }))); assertEquals("AAAK\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 10 }))); assertEquals("AAAL\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 11 }))); assertEquals("AAAM\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 12 }))); assertEquals("AAAN\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 13 }))); assertEquals("AAAO\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 14 }))); assertEquals("AAAP\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 15 }))); assertEquals("AAAQ\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 16 }))); assertEquals("AAAR\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 17 }))); assertEquals("AAAS\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 18 }))); assertEquals("AAAT\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 19 }))); assertEquals("AAAU\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 20 }))); assertEquals("AAAV\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 21 }))); assertEquals("AAAW\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 22 }))); assertEquals("AAAX\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 23 }))); assertEquals("AAAY\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 24 }))); assertEquals("AAAZ\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 25 }))); assertEquals("AAAa\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 26 }))); assertEquals("AAAb\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 27 }))); assertEquals("AAAc\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 28 }))); assertEquals("AAAd\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 29 }))); assertEquals("AAAe\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 30 }))); assertEquals("AAAf\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 31 }))); assertEquals("AAAg\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 32 }))); assertEquals("AAAh\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 33 }))); assertEquals("AAAi\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 34 }))); assertEquals("AAAj\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 35 }))); assertEquals("AAAk\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 36 }))); assertEquals("AAAl\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 37 }))); assertEquals("AAAm\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 38 }))); assertEquals("AAAn\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 39 }))); assertEquals("AAAo\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 40 }))); assertEquals("AAAp\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 41 }))); assertEquals("AAAq\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 42 }))); assertEquals("AAAr\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 43 }))); assertEquals("AAAs\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 44 }))); assertEquals("AAAt\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 45 }))); assertEquals("AAAu\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 46 }))); assertEquals("AAAv\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 47 }))); assertEquals("AAAw\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 48 }))); assertEquals("AAAx\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 49 }))); assertEquals("AAAy\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 50 }))); assertEquals("AAAz\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 51 }))); assertEquals("AAA0\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 52 }))); assertEquals("AAA1\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 53 }))); assertEquals("AAA2\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 54 }))); assertEquals("AAA3\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 55 }))); assertEquals("AAA4\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 56 }))); assertEquals("AAA5\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 57 }))); assertEquals("AAA6\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 58 }))); assertEquals("AAA7\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 59 }))); assertEquals("AAA8\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 60 }))); assertEquals("AAA9\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 61 }))); assertEquals("AAA+\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 62 }))); assertEquals("AAA/\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 63 }))); } /** * Tests url-safe Base64 against random data, sizes 0 to 150. */ @Test public void testUrlSafe() { // test random data of sizes 0 thru 150 for (int i = 0; i <= 150; i++) { final byte[][] randomData = Base64TestData.randomData(i, true); final byte[] encoded = randomData[1]; final byte[] decoded = randomData[0]; final byte[] result = Base64.decodeBase64(encoded); assertTrue("url-safe i=" + i, Arrays.equals(decoded, result)); assertFalse("url-safe i=" + i + " no '='", Base64TestData.bytesContain(encoded, (byte) '=')); assertFalse("url-safe i=" + i + " no '\\'", Base64TestData.bytesContain(encoded, (byte) '\\')); assertFalse("url-safe i=" + i + " no '+'", Base64TestData.bytesContain(encoded, (byte) '+')); } } /** * Base64 encoding of UUID's is a common use-case, especially in URL-SAFE * mode. This test case ends up being the "URL-SAFE" JUnit's. * * @throws DecoderException * if Hex.decode() fails - a serious problem since Hex comes * from our own commons-codec! */ @Test public void testUUID() throws DecoderException { // The 4 UUID's below contains mixtures of + and / to help us test the // URL-SAFE encoding mode. final byte[][] ids = new byte[4][]; // ids[0] was chosen so that it encodes with at least one +. ids[0] = Hex.decodeHex("94ed8d0319e4493399560fb67404d370"); // ids[1] was chosen so that it encodes with both / and +. ids[1] = Hex.decodeHex("2bf7cc2701fe4397b49ebeed5acc7090"); // ids[2] was chosen so that it encodes with at least one /. ids[2] = Hex.decodeHex("64be154b6ffa40258d1a01288e7c31ca"); // ids[3] was chosen so that it encodes with both / and +, with / // right at the beginning. ids[3] = Hex.decodeHex("ff7f8fc01cdb471a8c8b5a9306183fe8"); final byte[][] standard = new byte[4][]; standard[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg+2dATTcA=="); standard[1] = StringUtils.getBytesUtf8("K/fMJwH+Q5e0nr7tWsxwkA=="); standard[2] = StringUtils.getBytesUtf8("ZL4VS2/6QCWNGgEojnwxyg=="); standard[3] = StringUtils.getBytesUtf8("/3+PwBzbRxqMi1qTBhg/6A=="); final byte[][] urlSafe1 = new byte[4][]; // regular padding (two '==' signs). urlSafe1[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg-2dATTcA=="); urlSafe1[1] = StringUtils.getBytesUtf8("K_fMJwH-Q5e0nr7tWsxwkA=="); urlSafe1[2] = StringUtils.getBytesUtf8("ZL4VS2_6QCWNGgEojnwxyg=="); urlSafe1[3] = StringUtils.getBytesUtf8("_3-PwBzbRxqMi1qTBhg_6A=="); final byte[][] urlSafe2 = new byte[4][]; // single padding (only one '=' sign). urlSafe2[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg-2dATTcA="); urlSafe2[1] = StringUtils.getBytesUtf8("K_fMJwH-Q5e0nr7tWsxwkA="); urlSafe2[2] = StringUtils.getBytesUtf8("ZL4VS2_6QCWNGgEojnwxyg="); urlSafe2[3] = StringUtils.getBytesUtf8("_3-PwBzbRxqMi1qTBhg_6A="); final byte[][] urlSafe3 = new byte[4][]; // no padding (no '=' signs). urlSafe3[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg-2dATTcA"); urlSafe3[1] = StringUtils.getBytesUtf8("K_fMJwH-Q5e0nr7tWsxwkA"); urlSafe3[2] = StringUtils.getBytesUtf8("ZL4VS2_6QCWNGgEojnwxyg"); urlSafe3[3] = StringUtils.getBytesUtf8("_3-PwBzbRxqMi1qTBhg_6A"); for (int i = 0; i < 4; i++) { final byte[] encodedStandard = Base64.encodeBase64(ids[i]); final byte[] encodedUrlSafe = Base64.encodeBase64URLSafe(ids[i]); final byte[] decodedStandard = Base64.decodeBase64(standard[i]); final byte[] decodedUrlSafe1 = Base64.decodeBase64(urlSafe1[i]); final byte[] decodedUrlSafe2 = Base64.decodeBase64(urlSafe2[i]); final byte[] decodedUrlSafe3 = Base64.decodeBase64(urlSafe3[i]); // Very important debugging output should anyone // ever need to delve closely into this stuff. // { // System.out.println("reference: [" + Hex.encodeHexString(ids[i]) + "]"); // System.out.println("standard: [" + Hex.encodeHexString(decodedStandard) + "] From: [" // + StringUtils.newStringUtf8(standard[i]) + "]"); // System.out.println("safe1: [" + Hex.encodeHexString(decodedUrlSafe1) + "] From: [" // + StringUtils.newStringUtf8(urlSafe1[i]) + "]"); // System.out.println("safe2: [" + Hex.encodeHexString(decodedUrlSafe2) + "] From: [" // + StringUtils.newStringUtf8(urlSafe2[i]) + "]"); // System.out.println("safe3: [" + Hex.encodeHexString(decodedUrlSafe3) + "] From: [" // + StringUtils.newStringUtf8(urlSafe3[i]) + "]"); // } assertTrue("standard encode uuid", Arrays.equals(encodedStandard, standard[i])); assertTrue("url-safe encode uuid", Arrays.equals(encodedUrlSafe, urlSafe3[i])); assertTrue("standard decode uuid", Arrays.equals(decodedStandard, ids[i])); assertTrue("url-safe1 decode uuid", Arrays.equals(decodedUrlSafe1, ids[i])); assertTrue("url-safe2 decode uuid", Arrays.equals(decodedUrlSafe2, ids[i])); assertTrue("url-safe3 decode uuid", Arrays.equals(decodedUrlSafe3, ids[i])); } } @Test public void testByteToStringVariations() throws DecoderException { final Base64 base64 = new Base64(0); final byte[] b1 = StringUtils.getBytesUtf8("Hello World"); final byte[] b2 = new byte[0]; final byte[] b3 = null; final byte[] b4 = Hex.decodeHex("2bf7cc2701fe4397b49ebeed5acc7090"); // for // url-safe // tests assertEquals("byteToString Hello World", "SGVsbG8gV29ybGQ=", base64.encodeToString(b1)); assertEquals("byteToString static Hello World", "SGVsbG8gV29ybGQ=", Base64.encodeBase64String(b1)); assertEquals("byteToString \"\"", "", base64.encodeToString(b2)); assertEquals("byteToString static \"\"", "", Base64.encodeBase64String(b2)); assertEquals("byteToString null", null, base64.encodeToString(b3)); assertEquals("byteToString static null", null, Base64.encodeBase64String(b3)); assertEquals("byteToString UUID", "K/fMJwH+Q5e0nr7tWsxwkA==", base64.encodeToString(b4)); assertEquals("byteToString static UUID", "K/fMJwH+Q5e0nr7tWsxwkA==", Base64.encodeBase64String(b4)); assertEquals("byteToString static-url-safe UUID", "K_fMJwH-Q5e0nr7tWsxwkA", Base64.encodeBase64URLSafeString(b4)); } @Test public void testStringToByteVariations() throws DecoderException { final Base64 base64 = new Base64(); final String s1 = "SGVsbG8gV29ybGQ=\r\n"; final String s2 = ""; final String s3 = null; final String s4a = "K/fMJwH+Q5e0nr7tWsxwkA==\r\n"; final String s4b = "K_fMJwH-Q5e0nr7tWsxwkA"; final byte[] b4 = Hex.decodeHex("2bf7cc2701fe4397b49ebeed5acc7090"); // for // url-safe // tests assertEquals("StringToByte Hello World", "Hello World", StringUtils.newStringUtf8(base64.decode(s1))); assertEquals("StringToByte Hello World", "Hello World", StringUtils.newStringUtf8((byte[]) base64.decode((Object) s1))); assertEquals("StringToByte static Hello World", "Hello World", StringUtils.newStringUtf8(Base64.decodeBase64(s1))); assertEquals("StringToByte \"\"", "", StringUtils.newStringUtf8(base64.decode(s2))); assertEquals("StringToByte static \"\"", "", StringUtils.newStringUtf8(Base64.decodeBase64(s2))); assertEquals("StringToByte null", null, StringUtils.newStringUtf8(base64.decode(s3))); assertEquals("StringToByte static null", null, StringUtils.newStringUtf8(Base64.decodeBase64(s3))); assertTrue("StringToByte UUID", Arrays.equals(b4, base64.decode(s4b))); assertTrue("StringToByte static UUID", Arrays.equals(b4, Base64.decodeBase64(s4a))); assertTrue("StringToByte static-url-safe UUID", Arrays.equals(b4, Base64.decodeBase64(s4b))); } private String toString(final byte[] data) { final StringBuilder buf = new StringBuilder(); for (int i = 0; i < data.length; i++) { buf.append(data[i]); if (i != data.length - 1) { buf.append(","); } } return buf.toString(); } /** * Tests a lineSeparator much bigger than DEFAULT_BUFFER_SIZE. * * @see "<a href='http://mail-archives.apache.org/mod_mbox/commons-dev/201202.mbox/%3C4F3C85D7.5060706@snafu.de%3E'>dev@commons.apache.org</a>" */ @Test @Ignore public void testHugeLineSeparator() { final int BaseNCodec_DEFAULT_BUFFER_SIZE = 8192; final int Base64_BYTES_PER_ENCODED_BLOCK = 4; final byte[] baLineSeparator = new byte[BaseNCodec_DEFAULT_BUFFER_SIZE * 4 - 3]; final Base64 b64 = new Base64(Base64_BYTES_PER_ENCODED_BLOCK, baLineSeparator); final String strOriginal = "Hello World"; final String strDecoded = new String(b64.decode(b64.encode(StringUtils.getBytesUtf8(strOriginal)))); assertEquals("testDEFAULT_BUFFER_SIZE", strOriginal, strDecoded); } }
[ { "be_test_class_file": "org/apache/commons/codec/binary/Base64.java", "be_test_class_name": "org.apache.commons.codec.binary.Base64", "be_test_function_name": "decode", "be_test_function_signature": "([BIILorg/apache/commons/codec/binary/BaseNCodec$Context;)V", "line_numbers": [ "431", "432", "434", "435", "437", "438", "439", "440", "442", "443", "445", "446", "447", "448", "449", "450", "451", "452", "453", "462", "463", "467", "471", "473", "474", "475", "477", "478", "479", "480", "482", "485" ], "method_line_rate": 0.8125 }, { "be_test_class_file": "org/apache/commons/codec/binary/Base64.java", "be_test_class_name": "org.apache.commons.codec.binary.Base64", "be_test_function_name": "decodeBase64", "be_test_function_signature": "(Ljava/lang/String;)[B", "line_numbers": [ "693" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/codec/binary/Base64.java", "be_test_class_name": "org.apache.commons.codec.binary.Base64", "be_test_function_name": "isInAlphabet", "be_test_function_signature": "(B)Z", "line_numbers": [ "782" ], "method_line_rate": 1 } ]
public class QuarterTests extends TestCase
public void testDateConstructor1() { TimeZone zone = TimeZone.getTimeZone("GMT"); Calendar c = new GregorianCalendar(zone); Quarter q1 = new Quarter(new Date(1017619199999L), zone, Locale.getDefault()); Quarter q2 = new Quarter(new Date(1017619200000L), zone, Locale.getDefault()); assertEquals(1, q1.getQuarter()); assertEquals(1017619199999L, q1.getLastMillisecond(c)); assertEquals(2, q2.getQuarter()); assertEquals(1017619200000L, q2.getFirstMillisecond(c)); }
// // Abstract Java Tested Class // package org.jfree.data.time; // // import java.io.Serializable; // import java.util.Calendar; // import java.util.Date; // import java.util.Locale; // import java.util.TimeZone; // // // // public class Quarter extends RegularTimePeriod implements Serializable { // private static final long serialVersionUID = 3810061714380888671L; // public static final int FIRST_QUARTER = 1; // public static final int LAST_QUARTER = 4; // public static final int[] FIRST_MONTH_IN_QUARTER = { // 0, MonthConstants.JANUARY, MonthConstants.APRIL, MonthConstants.JULY, // MonthConstants.OCTOBER // }; // public static final int[] LAST_MONTH_IN_QUARTER = { // 0, MonthConstants.MARCH, MonthConstants.JUNE, MonthConstants.SEPTEMBER, // MonthConstants.DECEMBER // }; // private short year; // private byte quarter; // private long firstMillisecond; // private long lastMillisecond; // // public Quarter(); // public Quarter(int quarter, int year); // public Quarter(int quarter, Year year); // public Quarter(Date time); // public Quarter(Date time, TimeZone zone); // public Quarter(Date time, TimeZone zone, Locale locale); // public int getQuarter(); // public Year getYear(); // public int getYearValue(); // public long getFirstMillisecond(); // public long getLastMillisecond(); // public void peg(Calendar calendar); // public RegularTimePeriod previous(); // public RegularTimePeriod next(); // public long getSerialIndex(); // public boolean equals(Object obj); // public int hashCode(); // public int compareTo(Object o1); // public String toString(); // public long getFirstMillisecond(Calendar calendar); // public long getLastMillisecond(Calendar calendar); // public static Quarter parseQuarter(String s); // } // // // 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 java.util.Calendar; // import java.util.Date; // import java.util.GregorianCalendar; // import java.util.Locale; // import java.util.TimeZone; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.data.time.Quarter; // import org.jfree.data.time.TimePeriodFormatException; // import org.jfree.data.time.Year; // // // // public class QuarterTests extends TestCase { // private Quarter q1Y1900; // private Quarter q2Y1900; // private Quarter q3Y9999; // private Quarter q4Y9999; // // public static Test suite(); // public QuarterTests(String name); // protected void setUp(); // public void testEqualsSelf(); // public void testEquals(); // public void testDateConstructor1(); // public void testDateConstructor2(); // public void testQ1Y1900Previous(); // public void testQ1Y1900Next(); // public void testQ4Y9999Previous(); // public void testQ4Y9999Next(); // public void testParseQuarter(); // public void testSerialization(); // public void testHashcode(); // public void testNotCloneable(); // public void testConstructor(); // public void testGetFirstMillisecond(); // public void testGetFirstMillisecondWithTimeZone(); // public void testGetFirstMillisecondWithCalendar(); // public void testGetLastMillisecond(); // public void testGetLastMillisecondWithTimeZone(); // public void testGetLastMillisecondWithCalendar(); // public void testGetSerialIndex(); // public void testNext(); // public void testGetStart(); // public void testGetEnd(); // } // You are a professional Java test case writer, please create a test case named `testDateConstructor1` for the `Quarter` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * In GMT, the end of Q1 2002 is java.util.Date(1017619199999L). Use this * to check the quarter constructor. */
tests/org/jfree/data/time/junit/QuarterTests.java
package org.jfree.data.time; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone;
public Quarter(); public Quarter(int quarter, int year); public Quarter(int quarter, Year year); public Quarter(Date time); public Quarter(Date time, TimeZone zone); public Quarter(Date time, TimeZone zone, Locale locale); public int getQuarter(); public Year getYear(); public int getYearValue(); public long getFirstMillisecond(); public long getLastMillisecond(); public void peg(Calendar calendar); public RegularTimePeriod previous(); public RegularTimePeriod next(); public long getSerialIndex(); public boolean equals(Object obj); public int hashCode(); public int compareTo(Object o1); public String toString(); public long getFirstMillisecond(Calendar calendar); public long getLastMillisecond(Calendar calendar); public static Quarter parseQuarter(String s);
150
testDateConstructor1
```java // Abstract Java Tested Class package org.jfree.data.time; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class Quarter extends RegularTimePeriod implements Serializable { private static final long serialVersionUID = 3810061714380888671L; public static final int FIRST_QUARTER = 1; public static final int LAST_QUARTER = 4; public static final int[] FIRST_MONTH_IN_QUARTER = { 0, MonthConstants.JANUARY, MonthConstants.APRIL, MonthConstants.JULY, MonthConstants.OCTOBER }; public static final int[] LAST_MONTH_IN_QUARTER = { 0, MonthConstants.MARCH, MonthConstants.JUNE, MonthConstants.SEPTEMBER, MonthConstants.DECEMBER }; private short year; private byte quarter; private long firstMillisecond; private long lastMillisecond; public Quarter(); public Quarter(int quarter, int year); public Quarter(int quarter, Year year); public Quarter(Date time); public Quarter(Date time, TimeZone zone); public Quarter(Date time, TimeZone zone, Locale locale); public int getQuarter(); public Year getYear(); public int getYearValue(); public long getFirstMillisecond(); public long getLastMillisecond(); public void peg(Calendar calendar); public RegularTimePeriod previous(); public RegularTimePeriod next(); public long getSerialIndex(); public boolean equals(Object obj); public int hashCode(); public int compareTo(Object o1); public String toString(); public long getFirstMillisecond(Calendar calendar); public long getLastMillisecond(Calendar calendar); public static Quarter parseQuarter(String s); } // 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 java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.time.Quarter; import org.jfree.data.time.TimePeriodFormatException; import org.jfree.data.time.Year; public class QuarterTests extends TestCase { private Quarter q1Y1900; private Quarter q2Y1900; private Quarter q3Y9999; private Quarter q4Y9999; public static Test suite(); public QuarterTests(String name); protected void setUp(); public void testEqualsSelf(); public void testEquals(); public void testDateConstructor1(); public void testDateConstructor2(); public void testQ1Y1900Previous(); public void testQ1Y1900Next(); public void testQ4Y9999Previous(); public void testQ4Y9999Next(); public void testParseQuarter(); public void testSerialization(); public void testHashcode(); public void testNotCloneable(); public void testConstructor(); public void testGetFirstMillisecond(); public void testGetFirstMillisecondWithTimeZone(); public void testGetFirstMillisecondWithCalendar(); public void testGetLastMillisecond(); public void testGetLastMillisecondWithTimeZone(); public void testGetLastMillisecondWithCalendar(); public void testGetSerialIndex(); public void testNext(); public void testGetStart(); public void testGetEnd(); } ``` You are a professional Java test case writer, please create a test case named `testDateConstructor1` for the `Quarter` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * In GMT, the end of Q1 2002 is java.util.Date(1017619199999L). Use this * to check the quarter constructor. */
135
// // Abstract Java Tested Class // package org.jfree.data.time; // // import java.io.Serializable; // import java.util.Calendar; // import java.util.Date; // import java.util.Locale; // import java.util.TimeZone; // // // // public class Quarter extends RegularTimePeriod implements Serializable { // private static final long serialVersionUID = 3810061714380888671L; // public static final int FIRST_QUARTER = 1; // public static final int LAST_QUARTER = 4; // public static final int[] FIRST_MONTH_IN_QUARTER = { // 0, MonthConstants.JANUARY, MonthConstants.APRIL, MonthConstants.JULY, // MonthConstants.OCTOBER // }; // public static final int[] LAST_MONTH_IN_QUARTER = { // 0, MonthConstants.MARCH, MonthConstants.JUNE, MonthConstants.SEPTEMBER, // MonthConstants.DECEMBER // }; // private short year; // private byte quarter; // private long firstMillisecond; // private long lastMillisecond; // // public Quarter(); // public Quarter(int quarter, int year); // public Quarter(int quarter, Year year); // public Quarter(Date time); // public Quarter(Date time, TimeZone zone); // public Quarter(Date time, TimeZone zone, Locale locale); // public int getQuarter(); // public Year getYear(); // public int getYearValue(); // public long getFirstMillisecond(); // public long getLastMillisecond(); // public void peg(Calendar calendar); // public RegularTimePeriod previous(); // public RegularTimePeriod next(); // public long getSerialIndex(); // public boolean equals(Object obj); // public int hashCode(); // public int compareTo(Object o1); // public String toString(); // public long getFirstMillisecond(Calendar calendar); // public long getLastMillisecond(Calendar calendar); // public static Quarter parseQuarter(String s); // } // // // 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 java.util.Calendar; // import java.util.Date; // import java.util.GregorianCalendar; // import java.util.Locale; // import java.util.TimeZone; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.data.time.Quarter; // import org.jfree.data.time.TimePeriodFormatException; // import org.jfree.data.time.Year; // // // // public class QuarterTests extends TestCase { // private Quarter q1Y1900; // private Quarter q2Y1900; // private Quarter q3Y9999; // private Quarter q4Y9999; // // public static Test suite(); // public QuarterTests(String name); // protected void setUp(); // public void testEqualsSelf(); // public void testEquals(); // public void testDateConstructor1(); // public void testDateConstructor2(); // public void testQ1Y1900Previous(); // public void testQ1Y1900Next(); // public void testQ4Y9999Previous(); // public void testQ4Y9999Next(); // public void testParseQuarter(); // public void testSerialization(); // public void testHashcode(); // public void testNotCloneable(); // public void testConstructor(); // public void testGetFirstMillisecond(); // public void testGetFirstMillisecondWithTimeZone(); // public void testGetFirstMillisecondWithCalendar(); // public void testGetLastMillisecond(); // public void testGetLastMillisecondWithTimeZone(); // public void testGetLastMillisecondWithCalendar(); // public void testGetSerialIndex(); // public void testNext(); // public void testGetStart(); // public void testGetEnd(); // } // You are a professional Java test case writer, please create a test case named `testDateConstructor1` for the `Quarter` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * In GMT, the end of Q1 2002 is java.util.Date(1017619199999L). Use this * to check the quarter constructor. */ public void testDateConstructor1() {
/** * In GMT, the end of Q1 2002 is java.util.Date(1017619199999L). Use this * to check the quarter constructor. */
1
org.jfree.data.time.Quarter
tests
```java // Abstract Java Tested Class package org.jfree.data.time; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class Quarter extends RegularTimePeriod implements Serializable { private static final long serialVersionUID = 3810061714380888671L; public static final int FIRST_QUARTER = 1; public static final int LAST_QUARTER = 4; public static final int[] FIRST_MONTH_IN_QUARTER = { 0, MonthConstants.JANUARY, MonthConstants.APRIL, MonthConstants.JULY, MonthConstants.OCTOBER }; public static final int[] LAST_MONTH_IN_QUARTER = { 0, MonthConstants.MARCH, MonthConstants.JUNE, MonthConstants.SEPTEMBER, MonthConstants.DECEMBER }; private short year; private byte quarter; private long firstMillisecond; private long lastMillisecond; public Quarter(); public Quarter(int quarter, int year); public Quarter(int quarter, Year year); public Quarter(Date time); public Quarter(Date time, TimeZone zone); public Quarter(Date time, TimeZone zone, Locale locale); public int getQuarter(); public Year getYear(); public int getYearValue(); public long getFirstMillisecond(); public long getLastMillisecond(); public void peg(Calendar calendar); public RegularTimePeriod previous(); public RegularTimePeriod next(); public long getSerialIndex(); public boolean equals(Object obj); public int hashCode(); public int compareTo(Object o1); public String toString(); public long getFirstMillisecond(Calendar calendar); public long getLastMillisecond(Calendar calendar); public static Quarter parseQuarter(String s); } // 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 java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.time.Quarter; import org.jfree.data.time.TimePeriodFormatException; import org.jfree.data.time.Year; public class QuarterTests extends TestCase { private Quarter q1Y1900; private Quarter q2Y1900; private Quarter q3Y9999; private Quarter q4Y9999; public static Test suite(); public QuarterTests(String name); protected void setUp(); public void testEqualsSelf(); public void testEquals(); public void testDateConstructor1(); public void testDateConstructor2(); public void testQ1Y1900Previous(); public void testQ1Y1900Next(); public void testQ4Y9999Previous(); public void testQ4Y9999Next(); public void testParseQuarter(); public void testSerialization(); public void testHashcode(); public void testNotCloneable(); public void testConstructor(); public void testGetFirstMillisecond(); public void testGetFirstMillisecondWithTimeZone(); public void testGetFirstMillisecondWithCalendar(); public void testGetLastMillisecond(); public void testGetLastMillisecondWithTimeZone(); public void testGetLastMillisecondWithCalendar(); public void testGetSerialIndex(); public void testNext(); public void testGetStart(); public void testGetEnd(); } ``` You are a professional Java test case writer, please create a test case named `testDateConstructor1` for the `Quarter` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * In GMT, the end of Q1 2002 is java.util.Date(1017619199999L). Use this * to check the quarter constructor. */ public void testDateConstructor1() { ```
public class Quarter extends RegularTimePeriod implements 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 java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.time.Quarter; import org.jfree.data.time.TimePeriodFormatException; import org.jfree.data.time.Year;
public static Test suite(); public QuarterTests(String name); protected void setUp(); public void testEqualsSelf(); public void testEquals(); public void testDateConstructor1(); public void testDateConstructor2(); public void testQ1Y1900Previous(); public void testQ1Y1900Next(); public void testQ4Y9999Previous(); public void testQ4Y9999Next(); public void testParseQuarter(); public void testSerialization(); public void testHashcode(); public void testNotCloneable(); public void testConstructor(); public void testGetFirstMillisecond(); public void testGetFirstMillisecondWithTimeZone(); public void testGetFirstMillisecondWithCalendar(); public void testGetLastMillisecond(); public void testGetLastMillisecondWithTimeZone(); public void testGetLastMillisecondWithCalendar(); public void testGetSerialIndex(); public void testNext(); public void testGetStart(); public void testGetEnd();
0ba02ff7fd0493e77215bb8e0fc7275134751165c747cc7762e387d2e1b0e719
[ "org.jfree.data.time.junit.QuarterTests::testDateConstructor1" ]
private static final long serialVersionUID = 3810061714380888671L; public static final int FIRST_QUARTER = 1; public static final int LAST_QUARTER = 4; public static final int[] FIRST_MONTH_IN_QUARTER = { 0, MonthConstants.JANUARY, MonthConstants.APRIL, MonthConstants.JULY, MonthConstants.OCTOBER }; public static final int[] LAST_MONTH_IN_QUARTER = { 0, MonthConstants.MARCH, MonthConstants.JUNE, MonthConstants.SEPTEMBER, MonthConstants.DECEMBER }; private short year; private byte quarter; private long firstMillisecond; private long lastMillisecond;
public void testDateConstructor1()
private Quarter q1Y1900; private Quarter q2Y1900; private Quarter q3Y9999; private Quarter q4Y9999;
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.] * * ----------------- * QuarterTests.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); * 11-Jan-2005 : Added check for non-clonability (DG); * 05-Oct-2006 : Added some new tests (DG); * 11-Jul-2007 : Fixed bad time zone assumption (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 java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.time.Quarter; import org.jfree.data.time.TimePeriodFormatException; import org.jfree.data.time.Year; /** * Tests for the {link Quarter} class. */ public class QuarterTests extends TestCase { /** A quarter. */ private Quarter q1Y1900; /** A quarter. */ private Quarter q2Y1900; /** A quarter. */ private Quarter q3Y9999; /** A quarter. */ private Quarter q4Y9999; /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(QuarterTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public QuarterTests(String name) { super(name); } /** * Common test setup. */ protected void setUp() { this.q1Y1900 = new Quarter(1, 1900); this.q2Y1900 = new Quarter(2, 1900); this.q3Y9999 = new Quarter(3, 9999); this.q4Y9999 = new Quarter(4, 9999); } /** * Check that a Quarter instance is equal to itself. * * SourceForge Bug ID: 558850. */ public void testEqualsSelf() { Quarter quarter = new Quarter(); assertTrue(quarter.equals(quarter)); } /** * Tests the equals method. */ public void testEquals() { Quarter q1 = new Quarter(2, 2002); Quarter q2 = new Quarter(2, 2002); assertTrue(q1.equals(q2)); } /** * In GMT, the end of Q1 2002 is java.util.Date(1017619199999L). Use this * to check the quarter constructor. */ public void testDateConstructor1() { TimeZone zone = TimeZone.getTimeZone("GMT"); Calendar c = new GregorianCalendar(zone); Quarter q1 = new Quarter(new Date(1017619199999L), zone, Locale.getDefault()); Quarter q2 = new Quarter(new Date(1017619200000L), zone, Locale.getDefault()); assertEquals(1, q1.getQuarter()); assertEquals(1017619199999L, q1.getLastMillisecond(c)); assertEquals(2, q2.getQuarter()); assertEquals(1017619200000L, q2.getFirstMillisecond(c)); } /** * In Istanbul, the end of Q1 2002 is java.util.Date(1017608399999L). Use * this to check the quarter constructor. */ public void testDateConstructor2() { TimeZone zone = TimeZone.getTimeZone("Europe/Istanbul"); Calendar c = new GregorianCalendar(zone); Quarter q1 = new Quarter(new Date(1017608399999L), zone, Locale.getDefault()); Quarter q2 = new Quarter(new Date(1017608400000L), zone, Locale.getDefault()); assertEquals(1, q1.getQuarter()); assertEquals(1017608399999L, q1.getLastMillisecond(c)); assertEquals(2, q2.getQuarter()); assertEquals(1017608400000L, q2.getFirstMillisecond(c)); } /** * Set up a quarter equal to Q1 1900. Request the previous quarter, it * should be null. */ public void testQ1Y1900Previous() { Quarter previous = (Quarter) this.q1Y1900.previous(); assertNull(previous); } /** * Set up a quarter equal to Q1 1900. Request the next quarter, it should * be Q2 1900. */ public void testQ1Y1900Next() { Quarter next = (Quarter) this.q1Y1900.next(); assertEquals(this.q2Y1900, next); } /** * Set up a quarter equal to Q4 9999. Request the previous quarter, it * should be Q3 9999. */ public void testQ4Y9999Previous() { Quarter previous = (Quarter) this.q4Y9999.previous(); assertEquals(this.q3Y9999, previous); } /** * Set up a quarter equal to Q4 9999. Request the next quarter, it should * be null. */ public void testQ4Y9999Next() { Quarter next = (Quarter) this.q4Y9999.next(); assertNull(next); } /** * Test the string parsing code... */ public void testParseQuarter() { Quarter quarter = null; // test 1... try { quarter = Quarter.parseQuarter("Q1-2000"); } catch (TimePeriodFormatException e) { quarter = new Quarter(1, 1900); } assertEquals(1, quarter.getQuarter()); assertEquals(2000, quarter.getYear().getYear()); // test 2... try { quarter = Quarter.parseQuarter("2001-Q2"); } catch (TimePeriodFormatException e) { quarter = new Quarter(1, 1900); } assertEquals(2, quarter.getQuarter()); assertEquals(2001, quarter.getYear().getYear()); // test 3... try { quarter = Quarter.parseQuarter("Q3, 2002"); } catch (TimePeriodFormatException e) { quarter = new Quarter(1, 1900); } assertEquals(3, quarter.getQuarter()); assertEquals(2002, quarter.getYear().getYear()); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { Quarter q1 = new Quarter(4, 1999); Quarter q2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(q1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); q2 = (Quarter) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertEquals(q1, q2); } /** * Two objects that are equal are required to return the same hashCode. */ public void testHashcode() { Quarter q1 = new Quarter(2, 2003); Quarter q2 = new Quarter(2, 2003); assertTrue(q1.equals(q2)); int h1 = q1.hashCode(); int h2 = q2.hashCode(); assertEquals(h1, h2); } /** * The {@link Quarter} class is immutable, so should not be * {@link Cloneable}. */ public void testNotCloneable() { Quarter q = new Quarter(2, 2003); assertFalse(q instanceof Cloneable); } /** * Some tests for the constructor with (int, int) arguments. Covers bug * report 1377239. */ public void testConstructor() { boolean pass = false; try { /*Quarter q =*/ new Quarter(0, 2005); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); pass = false; try { /*Quarter q =*/ new Quarter(5, 2005); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); } /** * Some checks for the getFirstMillisecond() method. */ public void testGetFirstMillisecond() { Locale saved = Locale.getDefault(); Locale.setDefault(Locale.UK); TimeZone savedZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Quarter q = new Quarter(3, 1970); assertEquals(15634800000L, q.getFirstMillisecond()); Locale.setDefault(saved); TimeZone.setDefault(savedZone); } /** * Some checks for the getFirstMillisecond(TimeZone) method. */ public void testGetFirstMillisecondWithTimeZone() { Quarter q = new Quarter(2, 1950); TimeZone zone = TimeZone.getTimeZone("America/Los_Angeles"); Calendar c = new GregorianCalendar(zone); assertEquals(-623347200000L, q.getFirstMillisecond(c)); // try null calendar boolean pass = false; try { q.getFirstMillisecond((Calendar) null); } catch (NullPointerException e) { pass = true; } assertTrue(pass); } /** * Some checks for the getFirstMillisecond(TimeZone) method. */ public void testGetFirstMillisecondWithCalendar() { Quarter q = new Quarter(1, 2001); GregorianCalendar calendar = new GregorianCalendar(Locale.GERMANY); calendar.setTimeZone(TimeZone.getTimeZone("Europe/Frankfurt")); assertEquals(978307200000L, q.getFirstMillisecond(calendar)); // try null calendar boolean pass = false; try { q.getFirstMillisecond((Calendar) null); } catch (NullPointerException e) { pass = true; } assertTrue(pass); } /** * Some checks for the getLastMillisecond() method. */ public void testGetLastMillisecond() { Locale saved = Locale.getDefault(); Locale.setDefault(Locale.UK); TimeZone savedZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Quarter q = new Quarter(3, 1970); assertEquals(23583599999L, q.getLastMillisecond()); Locale.setDefault(saved); TimeZone.setDefault(savedZone); } /** * Some checks for the getLastMillisecond(TimeZone) method. */ public void testGetLastMillisecondWithTimeZone() { Quarter q = new Quarter(2, 1950); TimeZone zone = TimeZone.getTimeZone("America/Los_Angeles"); Calendar c = new GregorianCalendar(zone); assertEquals(-615488400001L, q.getLastMillisecond(c)); // try null calendar boolean pass = false; try { q.getLastMillisecond((Calendar) null); } catch (NullPointerException e) { pass = true; } assertTrue(pass); } /** * Some checks for the getLastMillisecond(TimeZone) method. */ public void testGetLastMillisecondWithCalendar() { Quarter q = new Quarter(3, 2001); GregorianCalendar calendar = new GregorianCalendar(Locale.GERMANY); calendar.setTimeZone(TimeZone.getTimeZone("Europe/Frankfurt")); assertEquals(1001894399999L, q.getLastMillisecond(calendar)); // try null calendar boolean pass = false; try { q.getLastMillisecond((Calendar) null); } catch (NullPointerException e) { pass = true; } assertTrue(pass); } /** * Some checks for the getSerialIndex() method. */ public void testGetSerialIndex() { Quarter q = new Quarter(1, 2000); assertEquals(8001L, q.getSerialIndex()); q = new Quarter(1, 1900); assertEquals(7601L, q.getSerialIndex()); } /** * Some checks for the testNext() method. */ public void testNext() { Quarter q = new Quarter(1, 2000); q = (Quarter) q.next(); assertEquals(new Year(2000), q.getYear()); assertEquals(2, q.getQuarter()); q = new Quarter(4, 9999); assertNull(q.next()); } /** * Some checks for the getStart() method. */ public void testGetStart() { Locale saved = Locale.getDefault(); Locale.setDefault(Locale.ITALY); Calendar cal = Calendar.getInstance(Locale.ITALY); cal.set(2006, Calendar.JULY, 1, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Quarter q = new Quarter(3, 2006); assertEquals(cal.getTime(), q.getStart()); Locale.setDefault(saved); } /** * Some checks for the getEnd() method. */ public void testGetEnd() { Locale saved = Locale.getDefault(); Locale.setDefault(Locale.ITALY); Calendar cal = Calendar.getInstance(Locale.ITALY); cal.set(2006, Calendar.MARCH, 31, 23, 59, 59); cal.set(Calendar.MILLISECOND, 999); Quarter q = new Quarter(1, 2006); assertEquals(cal.getTime(), q.getEnd()); Locale.setDefault(saved); } }
[ { "be_test_class_file": "org/jfree/data/time/Quarter.java", "be_test_class_name": "org.jfree.data.time.Quarter", "be_test_function_name": "getFirstMillisecond", "be_test_function_signature": "(Ljava/util/Calendar;)J", "line_numbers": [ "421", "422", "423", "426" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/Quarter.java", "be_test_class_name": "org.jfree.data.time.Quarter", "be_test_function_name": "getLastMillisecond", "be_test_function_signature": "(Ljava/util/Calendar;)J", "line_numbers": [ "441", "442", "443", "444", "447" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/Quarter.java", "be_test_class_name": "org.jfree.data.time.Quarter", "be_test_function_name": "getQuarter", "be_test_function_signature": "()I", "line_numbers": [ "197" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/Quarter.java", "be_test_class_name": "org.jfree.data.time.Quarter", "be_test_function_name": "peg", "be_test_function_signature": "(Ljava/util/Calendar;)V", "line_numbers": [ "257", "258", "259" ], "method_line_rate": 1 } ]
public class TimePeriodValuesCollectionTests extends TestCase
public void testGetDomainBoundsWithInterval() { // check empty dataset TimePeriodValuesCollection dataset = new TimePeriodValuesCollection(); Range r = dataset.getDomainBounds(true); assertNull(r); // check dataset with one time period TimePeriodValues s1 = new TimePeriodValues("S1"); s1.add(new SimpleTimePeriod(1000L, 2000L), 1.0); dataset.addSeries(s1); r = dataset.getDomainBounds(true); assertEquals(1000.0, r.getLowerBound(), EPSILON); assertEquals(2000.0, r.getUpperBound(), EPSILON); // check dataset with two time periods s1.add(new SimpleTimePeriod(1500L, 3000L), 2.0); r = dataset.getDomainBounds(true); assertEquals(1000.0, r.getLowerBound(), EPSILON); assertEquals(3000.0, r.getUpperBound(), EPSILON); // add a third time period s1.add(new SimpleTimePeriod(6000L, 7000L), 1.5); r = dataset.getDomainBounds(true); assertEquals(1000.0, r.getLowerBound(), EPSILON); assertEquals(7000.0, r.getUpperBound(), EPSILON); // add a fourth time period s1.add(new SimpleTimePeriod(4000L, 5000L), 1.4); r = dataset.getDomainBounds(true); assertEquals(1000.0, r.getLowerBound(), EPSILON); assertEquals(7000.0, r.getUpperBound(), EPSILON); }
// // Abstract Java Tested Class // package org.jfree.data.time; // // import java.io.Serializable; // import java.util.Iterator; // import java.util.List; // import org.jfree.chart.event.DatasetChangeInfo; // import org.jfree.chart.util.ObjectUtilities; // import org.jfree.data.DomainInfo; // import org.jfree.data.Range; // import org.jfree.data.xy.AbstractIntervalXYDataset; // import org.jfree.data.xy.IntervalXYDataset; // // // // public class TimePeriodValuesCollection extends AbstractIntervalXYDataset // implements IntervalXYDataset, DomainInfo, Serializable { // private static final long serialVersionUID = -3077934065236454199L; // private List data; // private TimePeriodAnchor xPosition; // // public TimePeriodValuesCollection(); // public TimePeriodValuesCollection(TimePeriodValues series); // public TimePeriodAnchor getXPosition(); // public void setXPosition(TimePeriodAnchor position); // public int getSeriesCount(); // public TimePeriodValues getSeries(int series); // public Comparable getSeriesKey(int series); // public void addSeries(TimePeriodValues series); // public void removeSeries(TimePeriodValues series); // public void removeSeries(int index); // public int getItemCount(int series); // public Number getX(int series, int item); // private long getX(TimePeriod period); // public Number getStartX(int series, int item); // public Number getEndX(int series, int item); // public Number getY(int series, int item); // public Number getStartY(int series, int item); // public Number getEndY(int series, int item); // public double getDomainLowerBound(boolean includeInterval); // public double getDomainUpperBound(boolean includeInterval); // public Range getDomainBounds(boolean includeInterval); // public boolean equals(Object obj); // } // // // 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.Range; // import org.jfree.data.time.Day; // import org.jfree.data.time.SimpleTimePeriod; // import org.jfree.data.time.TimePeriodAnchor; // import org.jfree.data.time.TimePeriodValues; // import org.jfree.data.time.TimePeriodValuesCollection; // // // // public class TimePeriodValuesCollectionTests extends TestCase { // private static final double EPSILON = 0.0000000001; // // public static Test suite(); // public TimePeriodValuesCollectionTests(String name); // protected void setUp(); // public void test1161340(); // public void testEquals(); // public void testSerialization(); // public void testGetSeries(); // public void testGetDomainBoundsWithoutInterval(); // public void testGetDomainBoundsWithInterval(); // } // You are a professional Java test case writer, please create a test case named `testGetDomainBoundsWithInterval` for the `TimePeriodValuesCollection` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Some more checks for the getDomainBounds() method. * * @see #testGetDomainBoundsWithoutInterval() */
tests/org/jfree/data/time/junit/TimePeriodValuesCollectionTests.java
package org.jfree.data.time; import java.io.Serializable; import java.util.Iterator; import java.util.List; import org.jfree.chart.event.DatasetChangeInfo; import org.jfree.chart.util.ObjectUtilities; import org.jfree.data.DomainInfo; import org.jfree.data.Range; import org.jfree.data.xy.AbstractIntervalXYDataset; import org.jfree.data.xy.IntervalXYDataset;
public TimePeriodValuesCollection(); public TimePeriodValuesCollection(TimePeriodValues series); public TimePeriodAnchor getXPosition(); public void setXPosition(TimePeriodAnchor position); public int getSeriesCount(); public TimePeriodValues getSeries(int series); public Comparable getSeriesKey(int series); public void addSeries(TimePeriodValues series); public void removeSeries(TimePeriodValues series); public void removeSeries(int index); public int getItemCount(int series); public Number getX(int series, int item); private long getX(TimePeriod period); public Number getStartX(int series, int item); public Number getEndX(int series, int item); public Number getY(int series, int item); public Number getStartY(int series, int item); public Number getEndY(int series, int item); public double getDomainLowerBound(boolean includeInterval); public double getDomainUpperBound(boolean includeInterval); public Range getDomainBounds(boolean includeInterval); public boolean equals(Object obj);
252
testGetDomainBoundsWithInterval
```java // Abstract Java Tested Class package org.jfree.data.time; import java.io.Serializable; import java.util.Iterator; import java.util.List; import org.jfree.chart.event.DatasetChangeInfo; import org.jfree.chart.util.ObjectUtilities; import org.jfree.data.DomainInfo; import org.jfree.data.Range; import org.jfree.data.xy.AbstractIntervalXYDataset; import org.jfree.data.xy.IntervalXYDataset; public class TimePeriodValuesCollection extends AbstractIntervalXYDataset implements IntervalXYDataset, DomainInfo, Serializable { private static final long serialVersionUID = -3077934065236454199L; private List data; private TimePeriodAnchor xPosition; public TimePeriodValuesCollection(); public TimePeriodValuesCollection(TimePeriodValues series); public TimePeriodAnchor getXPosition(); public void setXPosition(TimePeriodAnchor position); public int getSeriesCount(); public TimePeriodValues getSeries(int series); public Comparable getSeriesKey(int series); public void addSeries(TimePeriodValues series); public void removeSeries(TimePeriodValues series); public void removeSeries(int index); public int getItemCount(int series); public Number getX(int series, int item); private long getX(TimePeriod period); public Number getStartX(int series, int item); public Number getEndX(int series, int item); public Number getY(int series, int item); public Number getStartY(int series, int item); public Number getEndY(int series, int item); public double getDomainLowerBound(boolean includeInterval); public double getDomainUpperBound(boolean includeInterval); public Range getDomainBounds(boolean includeInterval); public boolean equals(Object obj); } // 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.Range; import org.jfree.data.time.Day; import org.jfree.data.time.SimpleTimePeriod; import org.jfree.data.time.TimePeriodAnchor; import org.jfree.data.time.TimePeriodValues; import org.jfree.data.time.TimePeriodValuesCollection; public class TimePeriodValuesCollectionTests extends TestCase { private static final double EPSILON = 0.0000000001; public static Test suite(); public TimePeriodValuesCollectionTests(String name); protected void setUp(); public void test1161340(); public void testEquals(); public void testSerialization(); public void testGetSeries(); public void testGetDomainBoundsWithoutInterval(); public void testGetDomainBoundsWithInterval(); } ``` You are a professional Java test case writer, please create a test case named `testGetDomainBoundsWithInterval` for the `TimePeriodValuesCollection` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Some more checks for the getDomainBounds() method. * * @see #testGetDomainBoundsWithoutInterval() */
221
// // Abstract Java Tested Class // package org.jfree.data.time; // // import java.io.Serializable; // import java.util.Iterator; // import java.util.List; // import org.jfree.chart.event.DatasetChangeInfo; // import org.jfree.chart.util.ObjectUtilities; // import org.jfree.data.DomainInfo; // import org.jfree.data.Range; // import org.jfree.data.xy.AbstractIntervalXYDataset; // import org.jfree.data.xy.IntervalXYDataset; // // // // public class TimePeriodValuesCollection extends AbstractIntervalXYDataset // implements IntervalXYDataset, DomainInfo, Serializable { // private static final long serialVersionUID = -3077934065236454199L; // private List data; // private TimePeriodAnchor xPosition; // // public TimePeriodValuesCollection(); // public TimePeriodValuesCollection(TimePeriodValues series); // public TimePeriodAnchor getXPosition(); // public void setXPosition(TimePeriodAnchor position); // public int getSeriesCount(); // public TimePeriodValues getSeries(int series); // public Comparable getSeriesKey(int series); // public void addSeries(TimePeriodValues series); // public void removeSeries(TimePeriodValues series); // public void removeSeries(int index); // public int getItemCount(int series); // public Number getX(int series, int item); // private long getX(TimePeriod period); // public Number getStartX(int series, int item); // public Number getEndX(int series, int item); // public Number getY(int series, int item); // public Number getStartY(int series, int item); // public Number getEndY(int series, int item); // public double getDomainLowerBound(boolean includeInterval); // public double getDomainUpperBound(boolean includeInterval); // public Range getDomainBounds(boolean includeInterval); // public boolean equals(Object obj); // } // // // 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.Range; // import org.jfree.data.time.Day; // import org.jfree.data.time.SimpleTimePeriod; // import org.jfree.data.time.TimePeriodAnchor; // import org.jfree.data.time.TimePeriodValues; // import org.jfree.data.time.TimePeriodValuesCollection; // // // // public class TimePeriodValuesCollectionTests extends TestCase { // private static final double EPSILON = 0.0000000001; // // public static Test suite(); // public TimePeriodValuesCollectionTests(String name); // protected void setUp(); // public void test1161340(); // public void testEquals(); // public void testSerialization(); // public void testGetSeries(); // public void testGetDomainBoundsWithoutInterval(); // public void testGetDomainBoundsWithInterval(); // } // You are a professional Java test case writer, please create a test case named `testGetDomainBoundsWithInterval` for the `TimePeriodValuesCollection` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Some more checks for the getDomainBounds() method. * * @see #testGetDomainBoundsWithoutInterval() */ public void testGetDomainBoundsWithInterval() {
/** * Some more checks for the getDomainBounds() method. * * @see #testGetDomainBoundsWithoutInterval() */
1
org.jfree.data.time.TimePeriodValuesCollection
tests
```java // Abstract Java Tested Class package org.jfree.data.time; import java.io.Serializable; import java.util.Iterator; import java.util.List; import org.jfree.chart.event.DatasetChangeInfo; import org.jfree.chart.util.ObjectUtilities; import org.jfree.data.DomainInfo; import org.jfree.data.Range; import org.jfree.data.xy.AbstractIntervalXYDataset; import org.jfree.data.xy.IntervalXYDataset; public class TimePeriodValuesCollection extends AbstractIntervalXYDataset implements IntervalXYDataset, DomainInfo, Serializable { private static final long serialVersionUID = -3077934065236454199L; private List data; private TimePeriodAnchor xPosition; public TimePeriodValuesCollection(); public TimePeriodValuesCollection(TimePeriodValues series); public TimePeriodAnchor getXPosition(); public void setXPosition(TimePeriodAnchor position); public int getSeriesCount(); public TimePeriodValues getSeries(int series); public Comparable getSeriesKey(int series); public void addSeries(TimePeriodValues series); public void removeSeries(TimePeriodValues series); public void removeSeries(int index); public int getItemCount(int series); public Number getX(int series, int item); private long getX(TimePeriod period); public Number getStartX(int series, int item); public Number getEndX(int series, int item); public Number getY(int series, int item); public Number getStartY(int series, int item); public Number getEndY(int series, int item); public double getDomainLowerBound(boolean includeInterval); public double getDomainUpperBound(boolean includeInterval); public Range getDomainBounds(boolean includeInterval); public boolean equals(Object obj); } // 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.Range; import org.jfree.data.time.Day; import org.jfree.data.time.SimpleTimePeriod; import org.jfree.data.time.TimePeriodAnchor; import org.jfree.data.time.TimePeriodValues; import org.jfree.data.time.TimePeriodValuesCollection; public class TimePeriodValuesCollectionTests extends TestCase { private static final double EPSILON = 0.0000000001; public static Test suite(); public TimePeriodValuesCollectionTests(String name); protected void setUp(); public void test1161340(); public void testEquals(); public void testSerialization(); public void testGetSeries(); public void testGetDomainBoundsWithoutInterval(); public void testGetDomainBoundsWithInterval(); } ``` You are a professional Java test case writer, please create a test case named `testGetDomainBoundsWithInterval` for the `TimePeriodValuesCollection` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Some more checks for the getDomainBounds() method. * * @see #testGetDomainBoundsWithoutInterval() */ public void testGetDomainBoundsWithInterval() { ```
public class TimePeriodValuesCollection extends AbstractIntervalXYDataset implements IntervalXYDataset, DomainInfo, 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.Range; import org.jfree.data.time.Day; import org.jfree.data.time.SimpleTimePeriod; import org.jfree.data.time.TimePeriodAnchor; import org.jfree.data.time.TimePeriodValues; import org.jfree.data.time.TimePeriodValuesCollection;
public static Test suite(); public TimePeriodValuesCollectionTests(String name); protected void setUp(); public void test1161340(); public void testEquals(); public void testSerialization(); public void testGetSeries(); public void testGetDomainBoundsWithoutInterval(); public void testGetDomainBoundsWithInterval();
0bcba3f18197f9fb514670eac8301174c25863bf6adafed26dc96ad0936cda1c
[ "org.jfree.data.time.junit.TimePeriodValuesCollectionTests::testGetDomainBoundsWithInterval" ]
private static final long serialVersionUID = -3077934065236454199L; private List data; private TimePeriodAnchor xPosition;
public void testGetDomainBoundsWithInterval()
private static final double EPSILON = 0.0000000001;
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.] * * ------------------------------------ * TimePeriodValuesCollectionTests.java * ------------------------------------ * (C) Copyright 2005-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 11-Mar-2005 : Version 1 (DG); * 08-Mar-2007 : Added testGetSeries() (DG); * 11-Jun-2007 : Added tests for getDomainBounds() (DG); * 20-Jun-2007 : Updated for deprecated method removals (DG); * 07-Apr-2008 : Added more checks to * testGetDomainBoundsWithInterval() (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.Range; import org.jfree.data.time.Day; import org.jfree.data.time.SimpleTimePeriod; import org.jfree.data.time.TimePeriodAnchor; import org.jfree.data.time.TimePeriodValues; import org.jfree.data.time.TimePeriodValuesCollection; /** * Some tests for the {@link TimePeriodValuesCollection} class. */ public class TimePeriodValuesCollectionTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(TimePeriodValuesCollectionTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public TimePeriodValuesCollectionTests(String name) { super(name); } /** * Common test setup. */ protected void setUp() { // no setup } /** * A test for bug report 1161340. I wasn't able to reproduce the problem * with this test. */ public void test1161340() { TimePeriodValuesCollection dataset = new TimePeriodValuesCollection(); TimePeriodValues v1 = new TimePeriodValues("V1"); v1.add(new Day(11, 3, 2005), 1.2); v1.add(new Day(12, 3, 2005), 3.4); dataset.addSeries(v1); assertEquals(1, dataset.getSeriesCount()); dataset.removeSeries(v1); assertEquals(0, dataset.getSeriesCount()); TimePeriodValues v2 = new TimePeriodValues("V2"); v1.add(new Day(5, 3, 2005), 1.2); v1.add(new Day(6, 3, 2005), 3.4); dataset.addSeries(v2); assertEquals(1, dataset.getSeriesCount()); } /** * Tests the equals() method. */ public void testEquals() { TimePeriodValuesCollection c1 = new TimePeriodValuesCollection(); TimePeriodValuesCollection c2 = new TimePeriodValuesCollection(); assertTrue(c1.equals(c2)); c1.setXPosition(TimePeriodAnchor.END); assertFalse(c1.equals(c2)); c2.setXPosition(TimePeriodAnchor.END); assertTrue(c1.equals(c2)); TimePeriodValues v1 = new TimePeriodValues("Test"); TimePeriodValues v2 = new TimePeriodValues("Test"); c1.addSeries(v1); assertFalse(c1.equals(c2)); c2.addSeries(v2); assertTrue(c1.equals(c2)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { TimePeriodValuesCollection c1 = new TimePeriodValuesCollection(); TimePeriodValuesCollection c2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(c1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); c2 = (TimePeriodValuesCollection) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(c1, c2); } /** * Some basic checks for the getSeries() method. */ public void testGetSeries() { TimePeriodValuesCollection c1 = new TimePeriodValuesCollection(); TimePeriodValues s1 = new TimePeriodValues("Series 1"); c1.addSeries(s1); assertEquals("Series 1", c1.getSeries(0).getKey()); boolean pass = false; try { c1.getSeries(-1); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); pass = false; try { c1.getSeries(1); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); } private static final double EPSILON = 0.0000000001; /** * Some checks for the getDomainBounds() method. */ public void testGetDomainBoundsWithoutInterval() { // check empty dataset TimePeriodValuesCollection dataset = new TimePeriodValuesCollection(); Range r = dataset.getDomainBounds(false); assertNull(r); // check dataset with one time period TimePeriodValues s1 = new TimePeriodValues("S1"); s1.add(new SimpleTimePeriod(1000L, 2000L), 1.0); dataset.addSeries(s1); r = dataset.getDomainBounds(false); assertEquals(1500.0, r.getLowerBound(), EPSILON); assertEquals(1500.0, r.getUpperBound(), EPSILON); // check dataset with two time periods s1.add(new SimpleTimePeriod(1500L, 3000L), 2.0); r = dataset.getDomainBounds(false); assertEquals(1500.0, r.getLowerBound(), EPSILON); assertEquals(2250.0, r.getUpperBound(), EPSILON); } /** * Some more checks for the getDomainBounds() method. * * @see #testGetDomainBoundsWithoutInterval() */ public void testGetDomainBoundsWithInterval() { // check empty dataset TimePeriodValuesCollection dataset = new TimePeriodValuesCollection(); Range r = dataset.getDomainBounds(true); assertNull(r); // check dataset with one time period TimePeriodValues s1 = new TimePeriodValues("S1"); s1.add(new SimpleTimePeriod(1000L, 2000L), 1.0); dataset.addSeries(s1); r = dataset.getDomainBounds(true); assertEquals(1000.0, r.getLowerBound(), EPSILON); assertEquals(2000.0, r.getUpperBound(), EPSILON); // check dataset with two time periods s1.add(new SimpleTimePeriod(1500L, 3000L), 2.0); r = dataset.getDomainBounds(true); assertEquals(1000.0, r.getLowerBound(), EPSILON); assertEquals(3000.0, r.getUpperBound(), EPSILON); // add a third time period s1.add(new SimpleTimePeriod(6000L, 7000L), 1.5); r = dataset.getDomainBounds(true); assertEquals(1000.0, r.getLowerBound(), EPSILON); assertEquals(7000.0, r.getUpperBound(), EPSILON); // add a fourth time period s1.add(new SimpleTimePeriod(4000L, 5000L), 1.4); r = dataset.getDomainBounds(true); assertEquals(1000.0, r.getLowerBound(), EPSILON); assertEquals(7000.0, r.getUpperBound(), EPSILON); } }
[ { "be_test_class_file": "org/jfree/data/time/TimePeriodValuesCollection.java", "be_test_class_name": "org.jfree.data.time.TimePeriodValuesCollection", "be_test_function_name": "addSeries", "be_test_function_signature": "(Lorg/jfree/data/time/TimePeriodValues;)V", "line_numbers": [ "179", "180", "183", "184", "185", "188" ], "method_line_rate": 0.8333333333333334 }, { "be_test_class_file": "org/jfree/data/time/TimePeriodValuesCollection.java", "be_test_class_name": "org.jfree.data.time.TimePeriodValuesCollection", "be_test_function_name": "getDomainBounds", "be_test_function_signature": "(Z)Lorg/jfree/data/Range;", "line_numbers": [ "381", "382", "383", "384", "385", "386", "387", "388", "390", "391", "392", "393", "395", "397", "398", "399", "401", "402", "403", "405", "406", "407", "409", "410", "411", "413", "415", "418", "421", "423", "424" ], "method_line_rate": 0.45161290322580644 } ]
public class TestJavaType extends BaseMapTest
public void testLocalType728() throws Exception { TypeFactory tf = TypeFactory.defaultInstance(); Method m = Issue728.class.getMethod("method", CharSequence.class); assertNotNull(m); // Start with return type // first type-erased JavaType t = tf.constructType(m.getReturnType()); assertEquals(CharSequence.class, t.getRawClass()); // then generic t = tf.constructType(m.getGenericReturnType()); assertEquals(CharSequence.class, t.getRawClass()); // then parameter type t = tf.constructType(m.getParameterTypes()[0]); assertEquals(CharSequence.class, t.getRawClass()); t = tf.constructType(m.getGenericParameterTypes()[0]); assertEquals(CharSequence.class, t.getRawClass()); }
// // Abstract Java Tested Class // package com.fasterxml.jackson.databind; // // import java.lang.reflect.Modifier; // import java.util.List; // import com.fasterxml.jackson.core.type.ResolvedType; // import com.fasterxml.jackson.databind.type.TypeBindings; // import com.fasterxml.jackson.databind.type.TypeFactory; // // // // public abstract class JavaType // extends ResolvedType // implements java.io.Serializable, // 2.1 // java.lang.reflect.Type // 2.2 // { // private static final long serialVersionUID = 1; // protected final Class<?> _class; // protected final int _hash; // protected final Object _valueHandler; // protected final Object _typeHandler; // protected final boolean _asStatic; // // protected JavaType(Class<?> raw, int additionalHash, // Object valueHandler, Object typeHandler, boolean asStatic); // protected JavaType(JavaType base); // public abstract JavaType withTypeHandler(Object h); // public abstract JavaType withContentTypeHandler(Object h); // public abstract JavaType withValueHandler(Object h); // public abstract JavaType withContentValueHandler(Object h); // public JavaType withHandlersFrom(JavaType src); // public abstract JavaType withContentType(JavaType contentType); // public abstract JavaType withStaticTyping(); // public abstract JavaType refine(Class<?> rawType, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // @Deprecated // public JavaType forcedNarrowBy(Class<?> subclass); // @Deprecated // since 2.7 // protected abstract JavaType _narrow(Class<?> subclass); // @Override // public final Class<?> getRawClass(); // @Override // public final boolean hasRawClass(Class<?> clz); // public boolean hasContentType(); // public final boolean isTypeOrSubTypeOf(Class<?> clz); // public final boolean isTypeOrSuperTypeOf(Class<?> clz); // @Override // public boolean isAbstract(); // @Override // public boolean isConcrete(); // @Override // public boolean isThrowable(); // @Override // public boolean isArrayType(); // @Override // public final boolean isEnumType(); // @Override // public final boolean isInterface(); // @Override // public final boolean isPrimitive(); // @Override // public final boolean isFinal(); // @Override // public abstract boolean isContainerType(); // @Override // public boolean isCollectionLikeType(); // @Override // public boolean isMapLikeType(); // public final boolean isJavaLangObject(); // public final boolean useStaticType(); // @Override // public boolean hasGenericTypes(); // @Override // public JavaType getKeyType(); // @Override // public JavaType getContentType(); // @Override // since 2.6 // public JavaType getReferencedType(); // @Override // public abstract int containedTypeCount(); // @Override // public abstract JavaType containedType(int index); // @Deprecated // since 2.7 // @Override // public abstract String containedTypeName(int index); // @Deprecated // since 2.7 // @Override // public Class<?> getParameterSource(); // public JavaType containedTypeOrUnknown(int index); // public abstract TypeBindings getBindings(); // public abstract JavaType findSuperType(Class<?> erasedTarget); // public abstract JavaType getSuperClass(); // public abstract List<JavaType> getInterfaces(); // public abstract JavaType[] findTypeParameters(Class<?> expType); // @SuppressWarnings("unchecked") // public <T> T getValueHandler(); // @SuppressWarnings("unchecked") // public <T> T getTypeHandler(); // public Object getContentValueHandler(); // public Object getContentTypeHandler(); // public boolean hasValueHandler(); // public boolean hasHandlers(); // public String getGenericSignature(); // public abstract StringBuilder getGenericSignature(StringBuilder sb); // public String getErasedSignature(); // public abstract StringBuilder getErasedSignature(StringBuilder sb); // @Override // public abstract String toString(); // @Override // public abstract boolean equals(Object o); // @Override // public final int hashCode(); // } // // // Abstract Java Test Class // package com.fasterxml.jackson.databind.type; // // import java.lang.reflect.Method; // import java.util.*; // import java.util.concurrent.atomic.AtomicReference; // import com.fasterxml.jackson.databind.BaseMapTest; // import com.fasterxml.jackson.databind.JavaType; // // // // public class TestJavaType // extends BaseMapTest // { // // // public void testLocalType728() throws Exception; // public void testSimpleClass(); // @SuppressWarnings("deprecation") // public void testDeprecated(); // public void testArrayType(); // public void testMapType(); // public void testEnumType(); // public void testClassKey(); // public void testJavaTypeAsJLRType(); // public void testGenericSignature1194() throws Exception; // public void testAnchorTypeForRefTypes() throws Exception; // public void testObjectToReferenceSpecialization() throws Exception; // public <C extends CharSequence> C method(C input); // } // You are a professional Java test case writer, please create a test case named `testLocalType728` for the `JavaType` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Test methods /********************************************************** */
src/test/java/com/fasterxml/jackson/databind/type/TestJavaType.java
package com.fasterxml.jackson.databind; import java.lang.reflect.Modifier; import java.util.List; import com.fasterxml.jackson.core.type.ResolvedType; import com.fasterxml.jackson.databind.type.TypeBindings; import com.fasterxml.jackson.databind.type.TypeFactory;
protected JavaType(Class<?> raw, int additionalHash, Object valueHandler, Object typeHandler, boolean asStatic); protected JavaType(JavaType base); public abstract JavaType withTypeHandler(Object h); public abstract JavaType withContentTypeHandler(Object h); public abstract JavaType withValueHandler(Object h); public abstract JavaType withContentValueHandler(Object h); public JavaType withHandlersFrom(JavaType src); public abstract JavaType withContentType(JavaType contentType); public abstract JavaType withStaticTyping(); public abstract JavaType refine(Class<?> rawType, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); @Deprecated public JavaType forcedNarrowBy(Class<?> subclass); @Deprecated // since 2.7 protected abstract JavaType _narrow(Class<?> subclass); @Override public final Class<?> getRawClass(); @Override public final boolean hasRawClass(Class<?> clz); public boolean hasContentType(); public final boolean isTypeOrSubTypeOf(Class<?> clz); public final boolean isTypeOrSuperTypeOf(Class<?> clz); @Override public boolean isAbstract(); @Override public boolean isConcrete(); @Override public boolean isThrowable(); @Override public boolean isArrayType(); @Override public final boolean isEnumType(); @Override public final boolean isInterface(); @Override public final boolean isPrimitive(); @Override public final boolean isFinal(); @Override public abstract boolean isContainerType(); @Override public boolean isCollectionLikeType(); @Override public boolean isMapLikeType(); public final boolean isJavaLangObject(); public final boolean useStaticType(); @Override public boolean hasGenericTypes(); @Override public JavaType getKeyType(); @Override public JavaType getContentType(); @Override // since 2.6 public JavaType getReferencedType(); @Override public abstract int containedTypeCount(); @Override public abstract JavaType containedType(int index); @Deprecated // since 2.7 @Override public abstract String containedTypeName(int index); @Deprecated // since 2.7 @Override public Class<?> getParameterSource(); public JavaType containedTypeOrUnknown(int index); public abstract TypeBindings getBindings(); public abstract JavaType findSuperType(Class<?> erasedTarget); public abstract JavaType getSuperClass(); public abstract List<JavaType> getInterfaces(); public abstract JavaType[] findTypeParameters(Class<?> expType); @SuppressWarnings("unchecked") public <T> T getValueHandler(); @SuppressWarnings("unchecked") public <T> T getTypeHandler(); public Object getContentValueHandler(); public Object getContentTypeHandler(); public boolean hasValueHandler(); public boolean hasHandlers(); public String getGenericSignature(); public abstract StringBuilder getGenericSignature(StringBuilder sb); public String getErasedSignature(); public abstract StringBuilder getErasedSignature(StringBuilder sb); @Override public abstract String toString(); @Override public abstract boolean equals(Object o); @Override public final int hashCode();
66
testLocalType728
```java // Abstract Java Tested Class package com.fasterxml.jackson.databind; import java.lang.reflect.Modifier; import java.util.List; import com.fasterxml.jackson.core.type.ResolvedType; import com.fasterxml.jackson.databind.type.TypeBindings; import com.fasterxml.jackson.databind.type.TypeFactory; public abstract class JavaType extends ResolvedType implements java.io.Serializable, // 2.1 java.lang.reflect.Type // 2.2 { private static final long serialVersionUID = 1; protected final Class<?> _class; protected final int _hash; protected final Object _valueHandler; protected final Object _typeHandler; protected final boolean _asStatic; protected JavaType(Class<?> raw, int additionalHash, Object valueHandler, Object typeHandler, boolean asStatic); protected JavaType(JavaType base); public abstract JavaType withTypeHandler(Object h); public abstract JavaType withContentTypeHandler(Object h); public abstract JavaType withValueHandler(Object h); public abstract JavaType withContentValueHandler(Object h); public JavaType withHandlersFrom(JavaType src); public abstract JavaType withContentType(JavaType contentType); public abstract JavaType withStaticTyping(); public abstract JavaType refine(Class<?> rawType, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); @Deprecated public JavaType forcedNarrowBy(Class<?> subclass); @Deprecated // since 2.7 protected abstract JavaType _narrow(Class<?> subclass); @Override public final Class<?> getRawClass(); @Override public final boolean hasRawClass(Class<?> clz); public boolean hasContentType(); public final boolean isTypeOrSubTypeOf(Class<?> clz); public final boolean isTypeOrSuperTypeOf(Class<?> clz); @Override public boolean isAbstract(); @Override public boolean isConcrete(); @Override public boolean isThrowable(); @Override public boolean isArrayType(); @Override public final boolean isEnumType(); @Override public final boolean isInterface(); @Override public final boolean isPrimitive(); @Override public final boolean isFinal(); @Override public abstract boolean isContainerType(); @Override public boolean isCollectionLikeType(); @Override public boolean isMapLikeType(); public final boolean isJavaLangObject(); public final boolean useStaticType(); @Override public boolean hasGenericTypes(); @Override public JavaType getKeyType(); @Override public JavaType getContentType(); @Override // since 2.6 public JavaType getReferencedType(); @Override public abstract int containedTypeCount(); @Override public abstract JavaType containedType(int index); @Deprecated // since 2.7 @Override public abstract String containedTypeName(int index); @Deprecated // since 2.7 @Override public Class<?> getParameterSource(); public JavaType containedTypeOrUnknown(int index); public abstract TypeBindings getBindings(); public abstract JavaType findSuperType(Class<?> erasedTarget); public abstract JavaType getSuperClass(); public abstract List<JavaType> getInterfaces(); public abstract JavaType[] findTypeParameters(Class<?> expType); @SuppressWarnings("unchecked") public <T> T getValueHandler(); @SuppressWarnings("unchecked") public <T> T getTypeHandler(); public Object getContentValueHandler(); public Object getContentTypeHandler(); public boolean hasValueHandler(); public boolean hasHandlers(); public String getGenericSignature(); public abstract StringBuilder getGenericSignature(StringBuilder sb); public String getErasedSignature(); public abstract StringBuilder getErasedSignature(StringBuilder sb); @Override public abstract String toString(); @Override public abstract boolean equals(Object o); @Override public final int hashCode(); } // Abstract Java Test Class package com.fasterxml.jackson.databind.type; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.databind.BaseMapTest; import com.fasterxml.jackson.databind.JavaType; public class TestJavaType extends BaseMapTest { public void testLocalType728() throws Exception; public void testSimpleClass(); @SuppressWarnings("deprecation") public void testDeprecated(); public void testArrayType(); public void testMapType(); public void testEnumType(); public void testClassKey(); public void testJavaTypeAsJLRType(); public void testGenericSignature1194() throws Exception; public void testAnchorTypeForRefTypes() throws Exception; public void testObjectToReferenceSpecialization() throws Exception; public <C extends CharSequence> C method(C input); } ``` You are a professional Java test case writer, please create a test case named `testLocalType728` for the `JavaType` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Test methods /********************************************************** */
47
// // Abstract Java Tested Class // package com.fasterxml.jackson.databind; // // import java.lang.reflect.Modifier; // import java.util.List; // import com.fasterxml.jackson.core.type.ResolvedType; // import com.fasterxml.jackson.databind.type.TypeBindings; // import com.fasterxml.jackson.databind.type.TypeFactory; // // // // public abstract class JavaType // extends ResolvedType // implements java.io.Serializable, // 2.1 // java.lang.reflect.Type // 2.2 // { // private static final long serialVersionUID = 1; // protected final Class<?> _class; // protected final int _hash; // protected final Object _valueHandler; // protected final Object _typeHandler; // protected final boolean _asStatic; // // protected JavaType(Class<?> raw, int additionalHash, // Object valueHandler, Object typeHandler, boolean asStatic); // protected JavaType(JavaType base); // public abstract JavaType withTypeHandler(Object h); // public abstract JavaType withContentTypeHandler(Object h); // public abstract JavaType withValueHandler(Object h); // public abstract JavaType withContentValueHandler(Object h); // public JavaType withHandlersFrom(JavaType src); // public abstract JavaType withContentType(JavaType contentType); // public abstract JavaType withStaticTyping(); // public abstract JavaType refine(Class<?> rawType, TypeBindings bindings, // JavaType superClass, JavaType[] superInterfaces); // @Deprecated // public JavaType forcedNarrowBy(Class<?> subclass); // @Deprecated // since 2.7 // protected abstract JavaType _narrow(Class<?> subclass); // @Override // public final Class<?> getRawClass(); // @Override // public final boolean hasRawClass(Class<?> clz); // public boolean hasContentType(); // public final boolean isTypeOrSubTypeOf(Class<?> clz); // public final boolean isTypeOrSuperTypeOf(Class<?> clz); // @Override // public boolean isAbstract(); // @Override // public boolean isConcrete(); // @Override // public boolean isThrowable(); // @Override // public boolean isArrayType(); // @Override // public final boolean isEnumType(); // @Override // public final boolean isInterface(); // @Override // public final boolean isPrimitive(); // @Override // public final boolean isFinal(); // @Override // public abstract boolean isContainerType(); // @Override // public boolean isCollectionLikeType(); // @Override // public boolean isMapLikeType(); // public final boolean isJavaLangObject(); // public final boolean useStaticType(); // @Override // public boolean hasGenericTypes(); // @Override // public JavaType getKeyType(); // @Override // public JavaType getContentType(); // @Override // since 2.6 // public JavaType getReferencedType(); // @Override // public abstract int containedTypeCount(); // @Override // public abstract JavaType containedType(int index); // @Deprecated // since 2.7 // @Override // public abstract String containedTypeName(int index); // @Deprecated // since 2.7 // @Override // public Class<?> getParameterSource(); // public JavaType containedTypeOrUnknown(int index); // public abstract TypeBindings getBindings(); // public abstract JavaType findSuperType(Class<?> erasedTarget); // public abstract JavaType getSuperClass(); // public abstract List<JavaType> getInterfaces(); // public abstract JavaType[] findTypeParameters(Class<?> expType); // @SuppressWarnings("unchecked") // public <T> T getValueHandler(); // @SuppressWarnings("unchecked") // public <T> T getTypeHandler(); // public Object getContentValueHandler(); // public Object getContentTypeHandler(); // public boolean hasValueHandler(); // public boolean hasHandlers(); // public String getGenericSignature(); // public abstract StringBuilder getGenericSignature(StringBuilder sb); // public String getErasedSignature(); // public abstract StringBuilder getErasedSignature(StringBuilder sb); // @Override // public abstract String toString(); // @Override // public abstract boolean equals(Object o); // @Override // public final int hashCode(); // } // // // Abstract Java Test Class // package com.fasterxml.jackson.databind.type; // // import java.lang.reflect.Method; // import java.util.*; // import java.util.concurrent.atomic.AtomicReference; // import com.fasterxml.jackson.databind.BaseMapTest; // import com.fasterxml.jackson.databind.JavaType; // // // // public class TestJavaType // extends BaseMapTest // { // // // public void testLocalType728() throws Exception; // public void testSimpleClass(); // @SuppressWarnings("deprecation") // public void testDeprecated(); // public void testArrayType(); // public void testMapType(); // public void testEnumType(); // public void testClassKey(); // public void testJavaTypeAsJLRType(); // public void testGenericSignature1194() throws Exception; // public void testAnchorTypeForRefTypes() throws Exception; // public void testObjectToReferenceSpecialization() throws Exception; // public <C extends CharSequence> C method(C input); // } // You are a professional Java test case writer, please create a test case named `testLocalType728` for the `JavaType` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Test methods /********************************************************** */ public void testLocalType728() throws Exception {
/* /********************************************************** /* Test methods /********************************************************** */
112
com.fasterxml.jackson.databind.JavaType
src/test/java
```java // Abstract Java Tested Class package com.fasterxml.jackson.databind; import java.lang.reflect.Modifier; import java.util.List; import com.fasterxml.jackson.core.type.ResolvedType; import com.fasterxml.jackson.databind.type.TypeBindings; import com.fasterxml.jackson.databind.type.TypeFactory; public abstract class JavaType extends ResolvedType implements java.io.Serializable, // 2.1 java.lang.reflect.Type // 2.2 { private static final long serialVersionUID = 1; protected final Class<?> _class; protected final int _hash; protected final Object _valueHandler; protected final Object _typeHandler; protected final boolean _asStatic; protected JavaType(Class<?> raw, int additionalHash, Object valueHandler, Object typeHandler, boolean asStatic); protected JavaType(JavaType base); public abstract JavaType withTypeHandler(Object h); public abstract JavaType withContentTypeHandler(Object h); public abstract JavaType withValueHandler(Object h); public abstract JavaType withContentValueHandler(Object h); public JavaType withHandlersFrom(JavaType src); public abstract JavaType withContentType(JavaType contentType); public abstract JavaType withStaticTyping(); public abstract JavaType refine(Class<?> rawType, TypeBindings bindings, JavaType superClass, JavaType[] superInterfaces); @Deprecated public JavaType forcedNarrowBy(Class<?> subclass); @Deprecated // since 2.7 protected abstract JavaType _narrow(Class<?> subclass); @Override public final Class<?> getRawClass(); @Override public final boolean hasRawClass(Class<?> clz); public boolean hasContentType(); public final boolean isTypeOrSubTypeOf(Class<?> clz); public final boolean isTypeOrSuperTypeOf(Class<?> clz); @Override public boolean isAbstract(); @Override public boolean isConcrete(); @Override public boolean isThrowable(); @Override public boolean isArrayType(); @Override public final boolean isEnumType(); @Override public final boolean isInterface(); @Override public final boolean isPrimitive(); @Override public final boolean isFinal(); @Override public abstract boolean isContainerType(); @Override public boolean isCollectionLikeType(); @Override public boolean isMapLikeType(); public final boolean isJavaLangObject(); public final boolean useStaticType(); @Override public boolean hasGenericTypes(); @Override public JavaType getKeyType(); @Override public JavaType getContentType(); @Override // since 2.6 public JavaType getReferencedType(); @Override public abstract int containedTypeCount(); @Override public abstract JavaType containedType(int index); @Deprecated // since 2.7 @Override public abstract String containedTypeName(int index); @Deprecated // since 2.7 @Override public Class<?> getParameterSource(); public JavaType containedTypeOrUnknown(int index); public abstract TypeBindings getBindings(); public abstract JavaType findSuperType(Class<?> erasedTarget); public abstract JavaType getSuperClass(); public abstract List<JavaType> getInterfaces(); public abstract JavaType[] findTypeParameters(Class<?> expType); @SuppressWarnings("unchecked") public <T> T getValueHandler(); @SuppressWarnings("unchecked") public <T> T getTypeHandler(); public Object getContentValueHandler(); public Object getContentTypeHandler(); public boolean hasValueHandler(); public boolean hasHandlers(); public String getGenericSignature(); public abstract StringBuilder getGenericSignature(StringBuilder sb); public String getErasedSignature(); public abstract StringBuilder getErasedSignature(StringBuilder sb); @Override public abstract String toString(); @Override public abstract boolean equals(Object o); @Override public final int hashCode(); } // Abstract Java Test Class package com.fasterxml.jackson.databind.type; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.databind.BaseMapTest; import com.fasterxml.jackson.databind.JavaType; public class TestJavaType extends BaseMapTest { public void testLocalType728() throws Exception; public void testSimpleClass(); @SuppressWarnings("deprecation") public void testDeprecated(); public void testArrayType(); public void testMapType(); public void testEnumType(); public void testClassKey(); public void testJavaTypeAsJLRType(); public void testGenericSignature1194() throws Exception; public void testAnchorTypeForRefTypes() throws Exception; public void testObjectToReferenceSpecialization() throws Exception; public <C extends CharSequence> C method(C input); } ``` You are a professional Java test case writer, please create a test case named `testLocalType728` for the `JavaType` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Test methods /********************************************************** */ public void testLocalType728() throws Exception { ```
public abstract class JavaType extends ResolvedType implements java.io.Serializable, // 2.1 java.lang.reflect.Type // 2.2
package com.fasterxml.jackson.databind.type; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.databind.BaseMapTest; import com.fasterxml.jackson.databind.JavaType;
public void testLocalType728() throws Exception; public void testSimpleClass(); @SuppressWarnings("deprecation") public void testDeprecated(); public void testArrayType(); public void testMapType(); public void testEnumType(); public void testClassKey(); public void testJavaTypeAsJLRType(); public void testGenericSignature1194() throws Exception; public void testAnchorTypeForRefTypes() throws Exception; public void testObjectToReferenceSpecialization() throws Exception; public <C extends CharSequence> C method(C input);
0d676cbccbd37177e90a562c831ea69a6dead74601d4b96dc0ab27c91142eafa
[ "com.fasterxml.jackson.databind.type.TestJavaType::testLocalType728" ]
private static final long serialVersionUID = 1; protected final Class<?> _class; protected final int _hash; protected final Object _valueHandler; protected final Object _typeHandler; protected final boolean _asStatic;
public void testLocalType728() throws Exception
JacksonDatabind
package com.fasterxml.jackson.databind.type; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.databind.BaseMapTest; import com.fasterxml.jackson.databind.JavaType; /** * Simple tests to verify that {@link JavaType} types work to * some degree */ public class TestJavaType extends BaseMapTest { static class BaseType { } static class SubType extends BaseType { } static enum MyEnum { A, B; } static enum MyEnum2 { A(1), B(2); private MyEnum2(int value) { } } // [databind#728] static class Issue728 { public <C extends CharSequence> C method(C input) { return null; } } public interface Generic1194 { public AtomicReference<String> getGeneric(); public List<String> getList(); public Map<String,String> getMap(); } @SuppressWarnings("serial") static class AtomicStringReference extends AtomicReference<String> { } /* /********************************************************** /* Test methods /********************************************************** */ public void testLocalType728() throws Exception { TypeFactory tf = TypeFactory.defaultInstance(); Method m = Issue728.class.getMethod("method", CharSequence.class); assertNotNull(m); // Start with return type // first type-erased JavaType t = tf.constructType(m.getReturnType()); assertEquals(CharSequence.class, t.getRawClass()); // then generic t = tf.constructType(m.getGenericReturnType()); assertEquals(CharSequence.class, t.getRawClass()); // then parameter type t = tf.constructType(m.getParameterTypes()[0]); assertEquals(CharSequence.class, t.getRawClass()); t = tf.constructType(m.getGenericParameterTypes()[0]); assertEquals(CharSequence.class, t.getRawClass()); } public void testSimpleClass() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType baseType = tf.constructType(BaseType.class); assertSame(BaseType.class, baseType.getRawClass()); assertTrue(baseType.hasRawClass(BaseType.class)); assertFalse(baseType.isTypeOrSubTypeOf(SubType.class)); assertFalse(baseType.isArrayType()); assertFalse(baseType.isContainerType()); assertFalse(baseType.isEnumType()); assertFalse(baseType.isInterface()); assertFalse(baseType.isPrimitive()); assertFalse(baseType.isReferenceType()); assertFalse(baseType.hasContentType()); assertNull(baseType.getContentType()); assertNull(baseType.getKeyType()); assertNull(baseType.getValueHandler()); assertEquals("Lcom/fasterxml/jackson/databind/type/TestJavaType$BaseType;", baseType.getGenericSignature()); assertEquals("Lcom/fasterxml/jackson/databind/type/TestJavaType$BaseType;", baseType.getErasedSignature()); } @SuppressWarnings("deprecation") public void testDeprecated() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType baseType = tf.constructType(BaseType.class); assertTrue(baseType.hasRawClass(BaseType.class)); assertNull(baseType.getParameterSource()); assertNull(baseType.getContentTypeHandler()); assertNull(baseType.getContentValueHandler()); assertFalse(baseType.hasValueHandler()); assertFalse(baseType.hasHandlers()); assertSame(baseType, baseType.forcedNarrowBy(BaseType.class)); JavaType sub = baseType.forcedNarrowBy(SubType.class); assertTrue(sub.hasRawClass(SubType.class)); } public void testArrayType() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType arrayT = ArrayType.construct(tf.constructType(String.class), null); assertNotNull(arrayT); assertTrue(arrayT.isContainerType()); assertFalse(arrayT.isReferenceType()); assertTrue(arrayT.hasContentType()); assertNotNull(arrayT.toString()); assertNotNull(arrayT.getContentType()); assertNull(arrayT.getKeyType()); assertTrue(arrayT.equals(arrayT)); assertFalse(arrayT.equals(null)); assertFalse(arrayT.equals("xyz")); assertTrue(arrayT.equals(ArrayType.construct(tf.constructType(String.class), null))); assertFalse(arrayT.equals(ArrayType.construct(tf.constructType(Integer.class), null))); } public void testMapType() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType mapT = tf.constructType(HashMap.class); assertTrue(mapT.isContainerType()); assertFalse(mapT.isReferenceType()); assertTrue(mapT.hasContentType()); assertNotNull(mapT.toString()); assertNotNull(mapT.getContentType()); assertNotNull(mapT.getKeyType()); assertEquals("Ljava/util/HashMap<Ljava/lang/Object;Ljava/lang/Object;>;", mapT.getGenericSignature()); assertEquals("Ljava/util/HashMap;", mapT.getErasedSignature()); assertTrue(mapT.equals(mapT)); assertFalse(mapT.equals(null)); assertFalse(mapT.equals("xyz")); } public void testEnumType() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType enumT = tf.constructType(MyEnum.class); assertTrue(enumT.isEnumType()); assertFalse(enumT.hasHandlers()); assertTrue(enumT.isTypeOrSubTypeOf(MyEnum.class)); assertTrue(enumT.isTypeOrSubTypeOf(Object.class)); assertNull(enumT.containedType(3)); assertTrue(enumT.containedTypeOrUnknown(3).isJavaLangObject()); assertEquals("Lcom/fasterxml/jackson/databind/type/TestJavaType$MyEnum;", enumT.getGenericSignature()); assertEquals("Lcom/fasterxml/jackson/databind/type/TestJavaType$MyEnum;", enumT.getErasedSignature()); assertTrue(tf.constructType(MyEnum2.class).isEnumType()); assertTrue(tf.constructType(MyEnum.A.getClass()).isEnumType()); assertTrue(tf.constructType(MyEnum2.A.getClass()).isEnumType()); } public void testClassKey() { ClassKey key = new ClassKey(String.class); assertEquals(0, key.compareTo(key)); assertTrue(key.equals(key)); assertFalse(key.equals(null)); assertFalse(key.equals("foo")); assertFalse(key.equals(new ClassKey(Integer.class))); assertEquals(String.class.getName(), key.toString()); } // [databind#116] public void testJavaTypeAsJLRType() { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t1 = tf.constructType(getClass()); // should just get it back as-is: JavaType t2 = tf.constructType(t1); assertSame(t1, t2); } // [databind#1194] public void testGenericSignature1194() throws Exception { TypeFactory tf = TypeFactory.defaultInstance(); Method m; JavaType t; m = Generic1194.class.getMethod("getList"); t = tf.constructType(m.getGenericReturnType()); assertEquals("Ljava/util/List<Ljava/lang/String;>;", t.getGenericSignature()); assertEquals("Ljava/util/List;", t.getErasedSignature()); m = Generic1194.class.getMethod("getMap"); t = tf.constructType(m.getGenericReturnType()); assertEquals("Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;", t.getGenericSignature()); m = Generic1194.class.getMethod("getGeneric"); t = tf.constructType(m.getGenericReturnType()); assertEquals("Ljava/util/concurrent/atomic/AtomicReference<Ljava/lang/String;>;", t.getGenericSignature()); } public void testAnchorTypeForRefTypes() throws Exception { TypeFactory tf = TypeFactory.defaultInstance(); JavaType t = tf.constructType(AtomicStringReference.class); assertTrue(t.isReferenceType()); assertTrue(t.hasContentType()); ReferenceType rt = (ReferenceType) t; assertFalse(rt.isAnchorType()); assertEquals(AtomicReference.class, rt.getAnchorType().getRawClass()); } // for [databind#1290] public void testObjectToReferenceSpecialization() throws Exception { TypeFactory tf = TypeFactory.defaultInstance(); JavaType base = tf.constructType(Object.class); assertTrue(base.isJavaLangObject()); JavaType sub = tf.constructSpecializedType(base, AtomicReference.class); assertEquals(AtomicReference.class, sub.getRawClass()); assertTrue(sub.isReferenceType()); } }
[ { "be_test_class_file": "com/fasterxml/jackson/databind/JavaType.java", "be_test_class_name": "com.fasterxml.jackson.databind.JavaType", "be_test_function_name": "getRawClass", "be_test_function_signature": "()Ljava/lang/Class;", "line_numbers": [ "227" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/JavaType.java", "be_test_class_name": "com.fasterxml.jackson.databind.JavaType", "be_test_function_name": "hasHandlers", "be_test_function_signature": "()Z", "line_numbers": [ "489" ], "method_line_rate": 1 } ]
public class TestTypeFactory extends BaseMapTest
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()); }
// 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 `testCollections` for the `TypeFactory` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Unit tests: collection type parameter resolution /********************************************************** */
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);
299
testCollections
```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 `testCollections` for the `TypeFactory` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Unit tests: collection type parameter resolution /********************************************************** */
277
// 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 `testCollections` for the `TypeFactory` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Unit tests: collection type parameter resolution /********************************************************** */ public void testCollections() {
/* /********************************************************** /* Unit tests: collection type parameter resolution /********************************************************** */
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 `testCollections` for the `TypeFactory` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Unit tests: collection type parameter resolution /********************************************************** */ public void testCollections() { ```
@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();
0e619b558937c405b63e04fd631da036fb5cd8d44a8650a8c38261b2582b00c5
[ "com.fasterxml.jackson.databind.type.TestTypeFactory::testCollections" ]
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 testCollections()
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.8461538461538461 }, { "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": "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": "constructCollectionType", "be_test_function_signature": "(Ljava/lang/Class;Ljava/lang/Class;)Lcom/fasterxml/jackson/databind/type/CollectionType;", "line_numbers": [ "734" ], "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": "(Lcom/fasterxml/jackson/core/type/TypeReference;)Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "641" ], "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 ChartPanelTests extends TestCase implements ChartChangeListener, ChartMouseListener
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()); }
// 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_zoomInRange` for the `ChartPanel` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Checks that a call to the zoomInRange() method, for a plot with more * than one range 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();
266
test2502355_zoomInRange
```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_zoomInRange` 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 zoomInRange() method, for a plot with more * than one range axis, generates just one ChartChangeEvent. */
255
// 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_zoomInRange` for the `ChartPanel` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * 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() {
/** * Checks that a call to the zoomInRange() method, for a plot with more * than one range 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_zoomInRange` 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 zoomInRange() method, for a plot with more * than one range axis, generates just one ChartChangeEvent. */ public void test2502355_zoomInRange() { ```
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();
11b55f009809888b81eff828ca5211becfbc7b51c16f6aae6bdaa569fae9d1f3
[ "org.jfree.chart.junit.ChartPanelTests::test2502355_zoomInRange" ]
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_zoomInRange()
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": "zoomInRange", "be_test_function_signature": "(DD)V", "line_numbers": [ "2139", "2140", "2144", "2145", "2146", "2147", "2150", "2152" ], "method_line_rate": 1 } ]
public class YIntervalSeriesCollectionTests extends TestCase
public void test1170825() { YIntervalSeries s1 = new YIntervalSeries("Series1"); YIntervalSeriesCollection dataset = new YIntervalSeriesCollection(); dataset.addSeries(s1); try { /* XYSeries s = */ dataset.getSeries(1); } catch (IllegalArgumentException e) { // correct outcome } catch (IndexOutOfBoundsException e) { assertTrue(false); // wrong outcome } }
// // Abstract Java Tested Class // package org.jfree.data.xy; // // import java.io.Serializable; // import java.util.List; // import org.jfree.chart.event.DatasetChangeInfo; // import org.jfree.chart.util.ObjectUtilities; // import org.jfree.chart.util.PublicCloneable; // import org.jfree.data.event.DatasetChangeEvent; // // // // public class YIntervalSeriesCollection extends AbstractIntervalXYDataset // implements IntervalXYDataset, PublicCloneable, Serializable { // private List data; // // public YIntervalSeriesCollection(); // public void addSeries(YIntervalSeries series); // public int getSeriesCount(); // public YIntervalSeries getSeries(int series); // public Comparable getSeriesKey(int series); // public int getItemCount(int series); // public Number getX(int series, int item); // public double getYValue(int series, int item); // public double getStartYValue(int series, int item); // public double getEndYValue(int series, int item); // public Number getY(int series, int item); // public Number getStartX(int series, int item); // public Number getEndX(int series, int item); // public Number getStartY(int series, int item); // public Number getEndY(int series, int item); // public void removeSeries(int series); // public void removeSeries(YIntervalSeries series); // public void removeAllSeries(); // public boolean equals(Object obj); // public Object clone() throws CloneNotSupportedException; // } // // // Abstract Java Test Class // package org.jfree.data.xy.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.chart.util.PublicCloneable; // import org.jfree.data.xy.YIntervalSeries; // import org.jfree.data.xy.YIntervalSeriesCollection; // // // // public class YIntervalSeriesCollectionTests extends TestCase { // // // public static Test suite(); // public YIntervalSeriesCollectionTests(String name); // public void testEquals(); // public void testCloning(); // public void testPublicCloneable(); // public void testSerialization(); // public void testRemoveSeries(); // public void test1170825(); // } // You are a professional Java test case writer, please create a test case named `test1170825` for the `YIntervalSeriesCollection` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * A test for bug report 1170825 (originally affected XYSeriesCollection, * this test is just copied over). */
tests/org/jfree/data/xy/junit/YIntervalSeriesCollectionTests.java
package org.jfree.data.xy; import java.io.Serializable; import java.util.List; import org.jfree.chart.event.DatasetChangeInfo; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.event.DatasetChangeEvent;
public YIntervalSeriesCollection(); public void addSeries(YIntervalSeries series); public int getSeriesCount(); public YIntervalSeries getSeries(int series); public Comparable getSeriesKey(int series); public int getItemCount(int series); public Number getX(int series, int item); public double getYValue(int series, int item); public double getStartYValue(int series, int item); public double getEndYValue(int series, int item); public Number getY(int series, int item); public Number getStartX(int series, int item); public Number getEndX(int series, int item); public Number getStartY(int series, int item); public Number getEndY(int series, int item); public void removeSeries(int series); public void removeSeries(YIntervalSeries series); public void removeAllSeries(); public boolean equals(Object obj); public Object clone() throws CloneNotSupportedException;
212
test1170825
```java // Abstract Java Tested Class package org.jfree.data.xy; import java.io.Serializable; import java.util.List; import org.jfree.chart.event.DatasetChangeInfo; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.event.DatasetChangeEvent; public class YIntervalSeriesCollection extends AbstractIntervalXYDataset implements IntervalXYDataset, PublicCloneable, Serializable { private List data; public YIntervalSeriesCollection(); public void addSeries(YIntervalSeries series); public int getSeriesCount(); public YIntervalSeries getSeries(int series); public Comparable getSeriesKey(int series); public int getItemCount(int series); public Number getX(int series, int item); public double getYValue(int series, int item); public double getStartYValue(int series, int item); public double getEndYValue(int series, int item); public Number getY(int series, int item); public Number getStartX(int series, int item); public Number getEndX(int series, int item); public Number getStartY(int series, int item); public Number getEndY(int series, int item); public void removeSeries(int series); public void removeSeries(YIntervalSeries series); public void removeAllSeries(); public boolean equals(Object obj); public Object clone() throws CloneNotSupportedException; } // Abstract Java Test Class package org.jfree.data.xy.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.chart.util.PublicCloneable; import org.jfree.data.xy.YIntervalSeries; import org.jfree.data.xy.YIntervalSeriesCollection; public class YIntervalSeriesCollectionTests extends TestCase { public static Test suite(); public YIntervalSeriesCollectionTests(String name); public void testEquals(); public void testCloning(); public void testPublicCloneable(); public void testSerialization(); public void testRemoveSeries(); public void test1170825(); } ``` You are a professional Java test case writer, please create a test case named `test1170825` for the `YIntervalSeriesCollection` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * A test for bug report 1170825 (originally affected XYSeriesCollection, * this test is just copied over). */
199
// // Abstract Java Tested Class // package org.jfree.data.xy; // // import java.io.Serializable; // import java.util.List; // import org.jfree.chart.event.DatasetChangeInfo; // import org.jfree.chart.util.ObjectUtilities; // import org.jfree.chart.util.PublicCloneable; // import org.jfree.data.event.DatasetChangeEvent; // // // // public class YIntervalSeriesCollection extends AbstractIntervalXYDataset // implements IntervalXYDataset, PublicCloneable, Serializable { // private List data; // // public YIntervalSeriesCollection(); // public void addSeries(YIntervalSeries series); // public int getSeriesCount(); // public YIntervalSeries getSeries(int series); // public Comparable getSeriesKey(int series); // public int getItemCount(int series); // public Number getX(int series, int item); // public double getYValue(int series, int item); // public double getStartYValue(int series, int item); // public double getEndYValue(int series, int item); // public Number getY(int series, int item); // public Number getStartX(int series, int item); // public Number getEndX(int series, int item); // public Number getStartY(int series, int item); // public Number getEndY(int series, int item); // public void removeSeries(int series); // public void removeSeries(YIntervalSeries series); // public void removeAllSeries(); // public boolean equals(Object obj); // public Object clone() throws CloneNotSupportedException; // } // // // Abstract Java Test Class // package org.jfree.data.xy.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.chart.util.PublicCloneable; // import org.jfree.data.xy.YIntervalSeries; // import org.jfree.data.xy.YIntervalSeriesCollection; // // // // public class YIntervalSeriesCollectionTests extends TestCase { // // // public static Test suite(); // public YIntervalSeriesCollectionTests(String name); // public void testEquals(); // public void testCloning(); // public void testPublicCloneable(); // public void testSerialization(); // public void testRemoveSeries(); // public void test1170825(); // } // You are a professional Java test case writer, please create a test case named `test1170825` for the `YIntervalSeriesCollection` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * A test for bug report 1170825 (originally affected XYSeriesCollection, * this test is just copied over). */ public void test1170825() {
/** * A test for bug report 1170825 (originally affected XYSeriesCollection, * this test is just copied over). */
1
org.jfree.data.xy.YIntervalSeriesCollection
tests
```java // Abstract Java Tested Class package org.jfree.data.xy; import java.io.Serializable; import java.util.List; import org.jfree.chart.event.DatasetChangeInfo; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.event.DatasetChangeEvent; public class YIntervalSeriesCollection extends AbstractIntervalXYDataset implements IntervalXYDataset, PublicCloneable, Serializable { private List data; public YIntervalSeriesCollection(); public void addSeries(YIntervalSeries series); public int getSeriesCount(); public YIntervalSeries getSeries(int series); public Comparable getSeriesKey(int series); public int getItemCount(int series); public Number getX(int series, int item); public double getYValue(int series, int item); public double getStartYValue(int series, int item); public double getEndYValue(int series, int item); public Number getY(int series, int item); public Number getStartX(int series, int item); public Number getEndX(int series, int item); public Number getStartY(int series, int item); public Number getEndY(int series, int item); public void removeSeries(int series); public void removeSeries(YIntervalSeries series); public void removeAllSeries(); public boolean equals(Object obj); public Object clone() throws CloneNotSupportedException; } // Abstract Java Test Class package org.jfree.data.xy.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.chart.util.PublicCloneable; import org.jfree.data.xy.YIntervalSeries; import org.jfree.data.xy.YIntervalSeriesCollection; public class YIntervalSeriesCollectionTests extends TestCase { public static Test suite(); public YIntervalSeriesCollectionTests(String name); public void testEquals(); public void testCloning(); public void testPublicCloneable(); public void testSerialization(); public void testRemoveSeries(); public void test1170825(); } ``` You are a professional Java test case writer, please create a test case named `test1170825` for the `YIntervalSeriesCollection` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * A test for bug report 1170825 (originally affected XYSeriesCollection, * this test is just copied over). */ public void test1170825() { ```
public class YIntervalSeriesCollection extends AbstractIntervalXYDataset implements IntervalXYDataset, PublicCloneable, Serializable
package org.jfree.data.xy.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.chart.util.PublicCloneable; import org.jfree.data.xy.YIntervalSeries; import org.jfree.data.xy.YIntervalSeriesCollection;
public static Test suite(); public YIntervalSeriesCollectionTests(String name); public void testEquals(); public void testCloning(); public void testPublicCloneable(); public void testSerialization(); public void testRemoveSeries(); public void test1170825();
11f55f2a23b466fce112f6edd9f5e153e0c77a813e297e5bc5a1566da3f6f57e
[ "org.jfree.data.xy.junit.YIntervalSeriesCollectionTests::test1170825" ]
private List data;
public void test1170825()
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.] * * ----------------------------------- * YIntervalSeriesCollectionTests.java * ----------------------------------- * (C) Copyright 2006-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 20-Oct-2006 : Version 1 (DG); * 18-Jan-2008 : Added testRemoveSeries() (DG); * 22-Apr-2008 : Added testPublicCloneable (DG); * */ package org.jfree.data.xy.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.chart.util.PublicCloneable; import org.jfree.data.xy.YIntervalSeries; import org.jfree.data.xy.YIntervalSeriesCollection; /** * Tests for the {@link YIntervalSeriesCollection} class. */ public class YIntervalSeriesCollectionTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(YIntervalSeriesCollectionTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public YIntervalSeriesCollectionTests(String name) { super(name); } /** * Confirm that the equals method can distinguish all the required fields. */ public void testEquals() { YIntervalSeriesCollection c1 = new YIntervalSeriesCollection(); YIntervalSeriesCollection c2 = new YIntervalSeriesCollection(); assertEquals(c1, c2); // add a series YIntervalSeries s1 = new YIntervalSeries("Series"); s1.add(1.0, 1.1, 1.2, 1.3); c1.addSeries(s1); assertFalse(c1.equals(c2)); YIntervalSeries s2 = new YIntervalSeries("Series"); s2.add(1.0, 1.1, 1.2, 1.3); c2.addSeries(s2); assertTrue(c1.equals(c2)); // add an empty series c1.addSeries(new YIntervalSeries("Empty Series")); assertFalse(c1.equals(c2)); c2.addSeries(new YIntervalSeries("Empty Series")); assertTrue(c1.equals(c2)); } /** * Confirm that cloning works. */ public void testCloning() { YIntervalSeriesCollection c1 = new YIntervalSeriesCollection(); YIntervalSeries s1 = new YIntervalSeries("Series"); s1.add(1.0, 1.1, 1.2, 1.3); c1.addSeries(s1); YIntervalSeriesCollection c2 = null; try { c2 = (YIntervalSeriesCollection) c1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(c1 != c2); assertTrue(c1.getClass() == c2.getClass()); assertTrue(c1.equals(c2)); // check independence s1.setDescription("XYZ"); assertFalse(c1.equals(c2)); } /** * Verify that this class implements {@link PublicCloneable}. */ public void testPublicCloneable() { YIntervalSeriesCollection c1 = new YIntervalSeriesCollection(); assertTrue(c1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { YIntervalSeriesCollection c1 = new YIntervalSeriesCollection(); YIntervalSeries s1 = new YIntervalSeries("Series"); s1.add(1.0, 1.1, 1.2, 1.3); YIntervalSeriesCollection c2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(c1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); c2 = (YIntervalSeriesCollection) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(c1, c2); } /** * Some basic checks for the removeSeries() method. */ public void testRemoveSeries() { YIntervalSeriesCollection c = new YIntervalSeriesCollection(); YIntervalSeries s1 = new YIntervalSeries("s1"); c.addSeries(s1); c.removeSeries(0); assertEquals(0, c.getSeriesCount()); c.addSeries(s1); boolean pass = false; try { c.removeSeries(-1); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); pass = false; try { c.removeSeries(1); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); } /** * A test for bug report 1170825 (originally affected XYSeriesCollection, * this test is just copied over). */ public void test1170825() { YIntervalSeries s1 = new YIntervalSeries("Series1"); YIntervalSeriesCollection dataset = new YIntervalSeriesCollection(); dataset.addSeries(s1); try { /* XYSeries s = */ dataset.getSeries(1); } catch (IllegalArgumentException e) { // correct outcome } catch (IndexOutOfBoundsException e) { assertTrue(false); // wrong outcome } } }
[ { "be_test_class_file": "org/jfree/data/xy/YIntervalSeriesCollection.java", "be_test_class_name": "org.jfree.data.xy.YIntervalSeriesCollection", "be_test_function_name": "addSeries", "be_test_function_signature": "(Lorg/jfree/data/xy/YIntervalSeries;)V", "line_numbers": [ "84", "85", "87", "88", "89", "91" ], "method_line_rate": 0.8333333333333334 }, { "be_test_class_file": "org/jfree/data/xy/YIntervalSeriesCollection.java", "be_test_class_name": "org.jfree.data.xy.YIntervalSeriesCollection", "be_test_function_name": "getSeries", "be_test_function_signature": "(I)Lorg/jfree/data/xy/YIntervalSeries;", "line_numbers": [ "113", "114", "116" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "org/jfree/data/xy/YIntervalSeriesCollection.java", "be_test_class_name": "org.jfree.data.xy.YIntervalSeriesCollection", "be_test_function_name": "getSeriesCount", "be_test_function_signature": "()I", "line_numbers": [ "99" ], "method_line_rate": 1 } ]
public class ChartPanelTests extends TestCase implements ChartChangeListener, ChartMouseListener
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()); }
// 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_restoreAutoDomainBounds` for the `ChartPanel` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Checks that a call to the restoreAutoDomainBounds() method, for a plot * with more than one range 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();
317
test2502355_restoreAutoDomainBounds
```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_restoreAutoDomainBounds` 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 restoreAutoDomainBounds() method, for a plot * with more than one range axis, generates just one ChartChangeEvent. */
306
// 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_restoreAutoDomainBounds` for the `ChartPanel` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * 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() {
/** * Checks that a call to the restoreAutoDomainBounds() method, for a plot * with more than one range 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_restoreAutoDomainBounds` 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 restoreAutoDomainBounds() method, for a plot * with more than one range axis, generates just one ChartChangeEvent. */ public void test2502355_restoreAutoDomainBounds() { ```
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();
120d4c313dabe9b92188839845983799ef35cdb6332a5452875330a3a399de04
[ "org.jfree.chart.junit.ChartPanelTests::test2502355_restoreAutoDomainBounds" ]
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_restoreAutoDomainBounds()
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": "restoreAutoDomainBounds", "be_test_function_signature": "()V", "line_numbers": [ "2294", "2295", "2296", "2300", "2301", "2303", "2305", "2306", "2308" ], "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": "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": "updateUI", "be_test_function_signature": "()V", "line_numbers": [ "2942", "2943", "2945", "2946" ], "method_line_rate": 0.75 } ]
public class FixedOrderComparatorTest extends AbstractComparatorTest<String>
@Test public void testConstructorPlusAdd() { final FixedOrderComparator<String> comparator = new FixedOrderComparator<String>(); for (final String topCitie : topCities) { comparator.add(topCitie); } final String[] keys = topCities.clone(); assertComparatorYieldsOrder(keys, comparator); }
// // Abstract Java Tested Class // package org.apache.commons.collections4.comparators; // // import java.io.Serializable; // import java.util.Comparator; // import java.util.HashMap; // import java.util.List; // import java.util.Map; // // // // public class FixedOrderComparator<T> implements Comparator<T>, Serializable { // private static final long serialVersionUID = 82794675842863201L; // private final Map<T, Integer> map = new HashMap<T, Integer>(); // private int counter = 0; // private boolean isLocked = false; // private UnknownObjectBehavior unknownObjectBehavior = UnknownObjectBehavior.EXCEPTION; // // public FixedOrderComparator(); // public FixedOrderComparator(final T... items); // public FixedOrderComparator(final List<T> items); // public boolean isLocked(); // protected void checkLocked(); // public UnknownObjectBehavior getUnknownObjectBehavior(); // public void setUnknownObjectBehavior(final UnknownObjectBehavior unknownObjectBehavior); // public boolean add(final T obj); // public boolean addAsEqual(final T existingObj, final T newObj); // @Override // public int compare(final T obj1, final T obj2); // @Override // public int hashCode(); // @Override // public boolean equals(final Object object); // } // // // Abstract Java Test Class // package org.apache.commons.collections4.comparators; // // import java.util.Arrays; // import java.util.Comparator; // import java.util.LinkedList; // import java.util.List; // import java.util.Random; // import org.junit.Test; // // // // public class FixedOrderComparatorTest extends AbstractComparatorTest<String> { // private static final String topCities[] = new String[] { // "Tokyo", // "Mexico City", // "Mumbai", // "Sao Paulo", // "New York", // "Shanghai", // "Lagos", // "Los Angeles", // "Calcutta", // "Buenos Aires" // }; // // public FixedOrderComparatorTest(final String name); // @Override // public Comparator<String> makeObject(); // @Override // public List<String> getComparableObjectsOrdered(); // @Override // public String getCompatibilityVersion(); // @Test // public void testConstructorPlusAdd(); // @Test // public void testArrayConstructor(); // @Test // public void testListConstructor(); // @Test // public void testAddAsEqual(); // @Test // public void testLock(); // @Test // public void testUnknownObjectBehavior(); // private void assertComparatorYieldsOrder(final String[] orderedObjects, // final Comparator<String> comparator); // } // You are a professional Java test case writer, please create a test case named `testConstructorPlusAdd` for the `FixedOrderComparator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests that the constructor plus add method compares items properly. */
src/test/java/org/apache/commons/collections4/comparators/FixedOrderComparatorTest.java
package org.apache.commons.collections4.comparators; import java.io.Serializable; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map;
public FixedOrderComparator(); public FixedOrderComparator(final T... items); public FixedOrderComparator(final List<T> items); public boolean isLocked(); protected void checkLocked(); public UnknownObjectBehavior getUnknownObjectBehavior(); public void setUnknownObjectBehavior(final UnknownObjectBehavior unknownObjectBehavior); public boolean add(final T obj); public boolean addAsEqual(final T existingObj, final T newObj); @Override public int compare(final T obj1, final T obj2); @Override public int hashCode(); @Override public boolean equals(final Object object);
96
testConstructorPlusAdd
```java // Abstract Java Tested Class package org.apache.commons.collections4.comparators; import java.io.Serializable; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; public class FixedOrderComparator<T> implements Comparator<T>, Serializable { private static final long serialVersionUID = 82794675842863201L; private final Map<T, Integer> map = new HashMap<T, Integer>(); private int counter = 0; private boolean isLocked = false; private UnknownObjectBehavior unknownObjectBehavior = UnknownObjectBehavior.EXCEPTION; public FixedOrderComparator(); public FixedOrderComparator(final T... items); public FixedOrderComparator(final List<T> items); public boolean isLocked(); protected void checkLocked(); public UnknownObjectBehavior getUnknownObjectBehavior(); public void setUnknownObjectBehavior(final UnknownObjectBehavior unknownObjectBehavior); public boolean add(final T obj); public boolean addAsEqual(final T existingObj, final T newObj); @Override public int compare(final T obj1, final T obj2); @Override public int hashCode(); @Override public boolean equals(final Object object); } // Abstract Java Test Class package org.apache.commons.collections4.comparators; import java.util.Arrays; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Random; import org.junit.Test; public class FixedOrderComparatorTest extends AbstractComparatorTest<String> { private static final String topCities[] = new String[] { "Tokyo", "Mexico City", "Mumbai", "Sao Paulo", "New York", "Shanghai", "Lagos", "Los Angeles", "Calcutta", "Buenos Aires" }; public FixedOrderComparatorTest(final String name); @Override public Comparator<String> makeObject(); @Override public List<String> getComparableObjectsOrdered(); @Override public String getCompatibilityVersion(); @Test public void testConstructorPlusAdd(); @Test public void testArrayConstructor(); @Test public void testListConstructor(); @Test public void testAddAsEqual(); @Test public void testLock(); @Test public void testUnknownObjectBehavior(); private void assertComparatorYieldsOrder(final String[] orderedObjects, final Comparator<String> comparator); } ``` You are a professional Java test case writer, please create a test case named `testConstructorPlusAdd` for the `FixedOrderComparator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests that the constructor plus add method compares items properly. */
88
// // Abstract Java Tested Class // package org.apache.commons.collections4.comparators; // // import java.io.Serializable; // import java.util.Comparator; // import java.util.HashMap; // import java.util.List; // import java.util.Map; // // // // public class FixedOrderComparator<T> implements Comparator<T>, Serializable { // private static final long serialVersionUID = 82794675842863201L; // private final Map<T, Integer> map = new HashMap<T, Integer>(); // private int counter = 0; // private boolean isLocked = false; // private UnknownObjectBehavior unknownObjectBehavior = UnknownObjectBehavior.EXCEPTION; // // public FixedOrderComparator(); // public FixedOrderComparator(final T... items); // public FixedOrderComparator(final List<T> items); // public boolean isLocked(); // protected void checkLocked(); // public UnknownObjectBehavior getUnknownObjectBehavior(); // public void setUnknownObjectBehavior(final UnknownObjectBehavior unknownObjectBehavior); // public boolean add(final T obj); // public boolean addAsEqual(final T existingObj, final T newObj); // @Override // public int compare(final T obj1, final T obj2); // @Override // public int hashCode(); // @Override // public boolean equals(final Object object); // } // // // Abstract Java Test Class // package org.apache.commons.collections4.comparators; // // import java.util.Arrays; // import java.util.Comparator; // import java.util.LinkedList; // import java.util.List; // import java.util.Random; // import org.junit.Test; // // // // public class FixedOrderComparatorTest extends AbstractComparatorTest<String> { // private static final String topCities[] = new String[] { // "Tokyo", // "Mexico City", // "Mumbai", // "Sao Paulo", // "New York", // "Shanghai", // "Lagos", // "Los Angeles", // "Calcutta", // "Buenos Aires" // }; // // public FixedOrderComparatorTest(final String name); // @Override // public Comparator<String> makeObject(); // @Override // public List<String> getComparableObjectsOrdered(); // @Override // public String getCompatibilityVersion(); // @Test // public void testConstructorPlusAdd(); // @Test // public void testArrayConstructor(); // @Test // public void testListConstructor(); // @Test // public void testAddAsEqual(); // @Test // public void testLock(); // @Test // public void testUnknownObjectBehavior(); // private void assertComparatorYieldsOrder(final String[] orderedObjects, // final Comparator<String> comparator); // } // You are a professional Java test case writer, please create a test case named `testConstructorPlusAdd` for the `FixedOrderComparator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests that the constructor plus add method compares items properly. */ // // The tests // // } // writeExternalFormToDisk((java.io.Serializable) makeObject(), "src/test/resources/data/test/FixedOrderComparator.version4.obj"); // public void testCreate() throws Exception { @Test public void testConstructorPlusAdd() {
/** * Tests that the constructor plus add method compares items properly. */ // // The tests // // } // writeExternalFormToDisk((java.io.Serializable) makeObject(), "src/test/resources/data/test/FixedOrderComparator.version4.obj"); // public void testCreate() throws Exception {
28
org.apache.commons.collections4.comparators.FixedOrderComparator
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.collections4.comparators; import java.io.Serializable; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; public class FixedOrderComparator<T> implements Comparator<T>, Serializable { private static final long serialVersionUID = 82794675842863201L; private final Map<T, Integer> map = new HashMap<T, Integer>(); private int counter = 0; private boolean isLocked = false; private UnknownObjectBehavior unknownObjectBehavior = UnknownObjectBehavior.EXCEPTION; public FixedOrderComparator(); public FixedOrderComparator(final T... items); public FixedOrderComparator(final List<T> items); public boolean isLocked(); protected void checkLocked(); public UnknownObjectBehavior getUnknownObjectBehavior(); public void setUnknownObjectBehavior(final UnknownObjectBehavior unknownObjectBehavior); public boolean add(final T obj); public boolean addAsEqual(final T existingObj, final T newObj); @Override public int compare(final T obj1, final T obj2); @Override public int hashCode(); @Override public boolean equals(final Object object); } // Abstract Java Test Class package org.apache.commons.collections4.comparators; import java.util.Arrays; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Random; import org.junit.Test; public class FixedOrderComparatorTest extends AbstractComparatorTest<String> { private static final String topCities[] = new String[] { "Tokyo", "Mexico City", "Mumbai", "Sao Paulo", "New York", "Shanghai", "Lagos", "Los Angeles", "Calcutta", "Buenos Aires" }; public FixedOrderComparatorTest(final String name); @Override public Comparator<String> makeObject(); @Override public List<String> getComparableObjectsOrdered(); @Override public String getCompatibilityVersion(); @Test public void testConstructorPlusAdd(); @Test public void testArrayConstructor(); @Test public void testListConstructor(); @Test public void testAddAsEqual(); @Test public void testLock(); @Test public void testUnknownObjectBehavior(); private void assertComparatorYieldsOrder(final String[] orderedObjects, final Comparator<String> comparator); } ``` You are a professional Java test case writer, please create a test case named `testConstructorPlusAdd` for the `FixedOrderComparator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests that the constructor plus add method compares items properly. */ // // The tests // // } // writeExternalFormToDisk((java.io.Serializable) makeObject(), "src/test/resources/data/test/FixedOrderComparator.version4.obj"); // public void testCreate() throws Exception { @Test public void testConstructorPlusAdd() { ```
public class FixedOrderComparator<T> implements Comparator<T>, Serializable
package org.apache.commons.collections4.comparators; import java.util.Arrays; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Random; import org.junit.Test;
public FixedOrderComparatorTest(final String name); @Override public Comparator<String> makeObject(); @Override public List<String> getComparableObjectsOrdered(); @Override public String getCompatibilityVersion(); @Test public void testConstructorPlusAdd(); @Test public void testArrayConstructor(); @Test public void testListConstructor(); @Test public void testAddAsEqual(); @Test public void testLock(); @Test public void testUnknownObjectBehavior(); private void assertComparatorYieldsOrder(final String[] orderedObjects, final Comparator<String> comparator);
125461b8ca4f4385e5689b7f74c4b9eca78c4101611bd7e99a12547ead401f84
[ "org.apache.commons.collections4.comparators.FixedOrderComparatorTest::testConstructorPlusAdd" ]
private static final long serialVersionUID = 82794675842863201L; private final Map<T, Integer> map = new HashMap<T, Integer>(); private int counter = 0; private boolean isLocked = false; private UnknownObjectBehavior unknownObjectBehavior = UnknownObjectBehavior.EXCEPTION;
@Test public void testConstructorPlusAdd()
private static final String topCities[] = new String[] { "Tokyo", "Mexico City", "Mumbai", "Sao Paulo", "New York", "Shanghai", "Lagos", "Los Angeles", "Calcutta", "Buenos Aires" };
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.comparators; import java.util.Arrays; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Random; import org.junit.Test; /** * Test class for FixedOrderComparator. * * @version $Id$ */ public class FixedOrderComparatorTest extends AbstractComparatorTest<String> { /** * Top cities of the world, by population including metro areas. */ private static final String topCities[] = new String[] { "Tokyo", "Mexico City", "Mumbai", "Sao Paulo", "New York", "Shanghai", "Lagos", "Los Angeles", "Calcutta", "Buenos Aires" }; // // Initialization and busywork // public FixedOrderComparatorTest(final String name) { super(name); } // // Set up and tear down // @Override public Comparator<String> makeObject() { final FixedOrderComparator<String> comparator = new FixedOrderComparator<String>(topCities); return comparator; } @Override public List<String> getComparableObjectsOrdered() { return Arrays.asList(topCities); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // writeExternalFormToDisk((java.io.Serializable) makeObject(), "src/test/resources/data/test/FixedOrderComparator.version4.obj"); // } // // The tests // /** * Tests that the constructor plus add method compares items properly. */ @Test public void testConstructorPlusAdd() { final FixedOrderComparator<String> comparator = new FixedOrderComparator<String>(); for (final String topCitie : topCities) { comparator.add(topCitie); } final String[] keys = topCities.clone(); assertComparatorYieldsOrder(keys, comparator); } /** * Tests that the array constructor compares items properly. */ @Test public void testArrayConstructor() { final String[] keys = topCities.clone(); final String[] topCitiesForTest = topCities.clone(); final FixedOrderComparator<String> comparator = new FixedOrderComparator<String>(topCitiesForTest); assertComparatorYieldsOrder(keys, comparator); // test that changing input after constructor has no effect topCitiesForTest[0] = "Brighton"; assertComparatorYieldsOrder(keys, comparator); } /** * Tests the list constructor. */ @Test public void testListConstructor() { final String[] keys = topCities.clone(); final List<String> topCitiesForTest = new LinkedList<String>(Arrays.asList(topCities)); final FixedOrderComparator<String> comparator = new FixedOrderComparator<String>(topCitiesForTest); assertComparatorYieldsOrder(keys, comparator); // test that changing input after constructor has no effect topCitiesForTest.set(0, "Brighton"); assertComparatorYieldsOrder(keys, comparator); } /** * Tests addAsEqual method. */ @Test public void testAddAsEqual() { final FixedOrderComparator<String> comparator = new FixedOrderComparator<String>(topCities); comparator.addAsEqual("New York", "Minneapolis"); assertEquals(0, comparator.compare("New York", "Minneapolis")); assertEquals(-1, comparator.compare("Tokyo", "Minneapolis")); assertEquals(1, comparator.compare("Shanghai", "Minneapolis")); } /** * Tests whether or not updates are disabled after a comparison is made. */ @Test public void testLock() { final FixedOrderComparator<String> comparator = new FixedOrderComparator<String>(topCities); assertEquals(false, comparator.isLocked()); comparator.compare("New York", "Tokyo"); assertEquals(true, comparator.isLocked()); try { comparator.add("Minneapolis"); fail("Should have thrown an UnsupportedOperationException"); } catch (final UnsupportedOperationException e) { // success -- ignore } try { comparator.addAsEqual("New York", "Minneapolis"); fail("Should have thrown an UnsupportedOperationException"); } catch (final UnsupportedOperationException e) { // success -- ignore } } @Test public void testUnknownObjectBehavior() { FixedOrderComparator<String> comparator = new FixedOrderComparator<String>(topCities); try { comparator.compare("New York", "Minneapolis"); fail("Should have thrown a IllegalArgumentException"); } catch (final IllegalArgumentException e) { // success-- ignore } try { comparator.compare("Minneapolis", "New York"); fail("Should have thrown a IllegalArgumentException"); } catch (final IllegalArgumentException e) { // success-- ignore } assertEquals(FixedOrderComparator.UnknownObjectBehavior.EXCEPTION, comparator.getUnknownObjectBehavior()); comparator = new FixedOrderComparator<String>(topCities); comparator.setUnknownObjectBehavior(FixedOrderComparator.UnknownObjectBehavior.BEFORE); assertEquals(FixedOrderComparator.UnknownObjectBehavior.BEFORE, comparator.getUnknownObjectBehavior()); LinkedList<String> keys = new LinkedList<String>(Arrays.asList(topCities)); keys.addFirst("Minneapolis"); assertComparatorYieldsOrder(keys.toArray(new String[0]), comparator); assertEquals(-1, comparator.compare("Minneapolis", "New York")); assertEquals( 1, comparator.compare("New York", "Minneapolis")); assertEquals( 0, comparator.compare("Minneapolis", "St Paul")); comparator = new FixedOrderComparator<String>(topCities); comparator.setUnknownObjectBehavior(FixedOrderComparator.UnknownObjectBehavior.AFTER); keys = new LinkedList<String>(Arrays.asList(topCities)); keys.add("Minneapolis"); assertComparatorYieldsOrder(keys.toArray(new String[0]), comparator); assertEquals( 1, comparator.compare("Minneapolis", "New York")); assertEquals(-1, comparator.compare("New York", "Minneapolis")); assertEquals( 0, comparator.compare("Minneapolis", "St Paul")); } // // Helper methods // /** Shuffles the keys and asserts that the comparator sorts them back to * their original order. */ private void assertComparatorYieldsOrder(final String[] orderedObjects, final Comparator<String> comparator) { final String[] keys = orderedObjects.clone(); // shuffle until the order changes. It's extremely rare that // this requires more than one shuffle. boolean isInNewOrder = false; final Random rand = new Random(); while (keys.length > 1 && !isInNewOrder) { // shuffle: for (int i = keys.length-1; i > 0; i--) { final String swap = keys[i]; final int j = rand.nextInt(i+1); keys[i] = keys[j]; keys[j] = swap; } // testShuffle for (int i = 0; i < keys.length && !isInNewOrder; i++) { if( !orderedObjects[i].equals(keys[i])) { isInNewOrder = true; } } } // The real test: sort and make sure they come out right. Arrays.sort(keys, comparator); for (int i = 0; i < orderedObjects.length; i++) { assertEquals(orderedObjects[i], keys[i]); } } }
[ { "be_test_class_file": "org/apache/commons/collections4/comparators/FixedOrderComparator.java", "be_test_class_name": "org.apache.commons.collections4.comparators.FixedOrderComparator", "be_test_function_name": "add", "be_test_function_signature": "(Ljava/lang/Object;)Z", "line_numbers": [ "183", "184", "185" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/collections4/comparators/FixedOrderComparator.java", "be_test_class_name": "org.apache.commons.collections4.comparators.FixedOrderComparator", "be_test_function_name": "checkLocked", "be_test_function_signature": "()V", "line_numbers": [ "140", "141", "143" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "org/apache/commons/collections4/comparators/FixedOrderComparator.java", "be_test_class_name": "org.apache.commons.collections4.comparators.FixedOrderComparator", "be_test_function_name": "compare", "be_test_function_signature": "(Ljava/lang/Object;Ljava/lang/Object;)I", "line_numbers": [ "229", "230", "231", "232", "233", "235", "237", "239", "240", "243", "247" ], "method_line_rate": 0.45454545454545453 }, { "be_test_class_file": "org/apache/commons/collections4/comparators/FixedOrderComparator.java", "be_test_class_name": "org.apache.commons.collections4.comparators.FixedOrderComparator", "be_test_function_name": "isLocked", "be_test_function_signature": "()Z", "line_numbers": [ "131" ], "method_line_rate": 1 } ]
public class SegmentedTimelineTests extends TestCase
public void testFifteenMinSegmentedTimeline() { assertEquals(SegmentedTimeline.FIFTEEN_MINUTE_SEGMENT_SIZE, this.fifteenMinTimeline.getSegmentSize()); assertEquals(SegmentedTimeline.FIRST_MONDAY_AFTER_1900 + 36 * this.fifteenMinTimeline.getSegmentSize(), this.fifteenMinTimeline.getStartTime()); assertEquals(28, this.fifteenMinTimeline.getSegmentsIncluded()); assertEquals(68, this.fifteenMinTimeline.getSegmentsExcluded()); }
// "2000-12-25", "2001-01-01", "2001-01-15", "2001-02-19", "2001-04-13", // "2001-05-28", "2001-07-04", "2001-09-03", "2001-09-11", "2001-09-12", // "2001-09-13", "2001-09-14", "2001-11-22", "2001-12-25", "2002-01-01", // "2002-01-21", "2002-02-18", "2002-03-29", "2002-05-27", "2002-07-04", // "2002-09-02", "2002-11-28", "2002-12-25"}; // private static final String[] FIFTEEN_MIN_EXCEPTIONS = { // "2000-01-10 09:00:00", "2000-01-10 09:15:00", "2000-01-10 09:30:00", // "2000-01-10 09:45:00", "2000-01-10 10:00:00", "2000-01-10 10:15:00", // "2000-02-15 09:00:00", "2000-02-15 09:15:00", "2000-02-15 09:30:00", // "2000-02-15 09:45:00", "2000-02-15 10:00:00", "2000-02-15 10:15:00", // "2000-02-16 11:00:00", "2000-02-16 11:15:00", "2000-02-16 11:30:00", // "2000-02-16 11:45:00", "2000-02-16 12:00:00", "2000-02-16 12:15:00", // "2000-02-16 12:30:00", "2000-02-16 12:45:00", "2000-02-16 01:00:00", // "2000-02-16 01:15:00", "2000-02-16 01:30:00", "2000-02-16 01:45:00", // "2000-05-17 11:45:00", "2000-05-17 12:00:00", "2000-05-17 12:15:00", // "2000-05-17 12:30:00", "2000-05-17 12:45:00", "2000-05-17 01:00:00", // "2000-05-17 01:15:00", "2000-05-17 01:30:00", "2000-05-17 01:45:00", // "2000-05-17 02:00:00", "2000-05-17 02:15:00", "2000-05-17 02:30:00", // "2000-05-17 02:45:00", "2000-05-17 03:00:00", "2000-05-17 03:15:00", // "2000-05-17 03:30:00", "2000-05-17 03:45:00", "2000-05-17 04:00:00"}; // private SegmentedTimeline msTimeline; // private SegmentedTimeline ms2Timeline; // private SegmentedTimeline ms2BaseTimeline; // private SegmentedTimeline mondayFridayTimeline; // private SegmentedTimeline fifteenMinTimeline; // private Calendar monday; // private Calendar monday9am; // // public static Test suite(); // public SegmentedTimelineTests(String name); // protected void setUp() throws Exception; // protected void tearDown() throws Exception; // public void testMsSegmentedTimeline(); // public void testMs2SegmentedTimeline(); // public void testMondayThroughFridaySegmentedTimeline(); // public void testFifteenMinSegmentedTimeline(); // public void testMsSegment(); // public void testMs2Segment(); // public void testMondayThroughFridaySegment(); // public void testFifteenMinSegment(); // public void verifyOneSegment(SegmentedTimeline timeline); // public void testMsInc(); // public void testMs2Inc(); // public void testMondayThroughFridayInc(); // public void testFifteenMinInc(); // public void verifyInc(SegmentedTimeline timeline); // public void testMsIncludedAndExcludedSegments(); // public void testMs2IncludedAndExcludedSegments(); // public void testMondayThroughFridayIncludedAndExcludedSegments(); // public void testFifteenMinIncludedAndExcludedSegments(); // public void verifyIncludedAndExcludedSegments(SegmentedTimeline timeline, // long n); // public void testMsExceptionSegments() throws ParseException; // public void testMs2BaseTimelineExceptionSegments() throws ParseException; // public void testMondayThoughFridayExceptionSegments() // throws ParseException; // public void testFifteenMinExceptionSegments() throws ParseException; // public void verifyExceptionSegments(SegmentedTimeline timeline, // String[] exceptionString, // Format fmt) // throws ParseException; // public void testMsTranslations() throws ParseException; // public void testMs2BaseTimelineTranslations() throws ParseException; // public void testMs2Translations() throws ParseException; // public void textMondayThroughFridayTranslations() throws ParseException; // public void testFifteenMinTranslations() throws ParseException; // public void verifyTranslations(SegmentedTimeline timeline, long startTest); // public void testSerialization(); // private void verifySerialization(SegmentedTimeline a1); // private long[] verifyFillInExceptions(SegmentedTimeline timeline, // String[] exceptionString, // Format fmt) throws ParseException; // private void fillInBaseTimelineExceptions(SegmentedTimeline timeline, // String[] exceptionString, // Format fmt) throws ParseException; // private void fillInBaseTimelineExclusionsAsExceptions( // SegmentedTimeline timeline, long from, long to); // public void testCloning(); // public void testEquals(); // public void testHashCode(); // public void testSerialization2(); // public void testBasicSegmentedTimeline(); // public void testSegmentedTimelineWithException1(); // public static void main(String[] args) throws Exception; // } // You are a professional Java test case writer, please create a test case named `testFifteenMinSegmentedTimeline` for the `SegmentedTimeline` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests that the factory method that creates a 15-min 9:00 AM 4:00 PM * segmented axis does so correctly. */
tests/org/jfree/chart/axis/junit/SegmentedTimelineTests.java
package org.jfree.chart.axis; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.SimpleTimeZone; import java.util.TimeZone;
public SegmentedTimeline(long segmentSize, int segmentsIncluded, int segmentsExcluded); public static long firstMondayAfter1900(); public static SegmentedTimeline newMondayThroughFridayTimeline(); public static SegmentedTimeline newFifteenMinuteTimeline(); public boolean getAdjustForDaylightSaving(); public void setAdjustForDaylightSaving(boolean adjust); public void setStartTime(long millisecond); public long getStartTime(); public int getSegmentsExcluded(); public long getSegmentsExcludedSize(); public int getGroupSegmentCount(); public long getSegmentsGroupSize(); public int getSegmentsIncluded(); public long getSegmentsIncludedSize(); public long getSegmentSize(); public List getExceptionSegments(); public void setExceptionSegments(List exceptionSegments); public SegmentedTimeline getBaseTimeline(); public void setBaseTimeline(SegmentedTimeline baseTimeline); public long toTimelineValue(long millisecond); public long toTimelineValue(Date date); public long toMillisecond(long timelineValue); public long getTimeFromLong(long date); public boolean containsDomainValue(long millisecond); public boolean containsDomainValue(Date date); public boolean containsDomainRange(long domainValueStart, long domainValueEnd); public boolean containsDomainRange(Date dateDomainValueStart, Date dateDomainValueEnd); public void addException(long millisecond); public void addException(long fromDomainValue, long toDomainValue); public void addException(Date exceptionDate); public void addExceptions(List exceptionList); private void addException(Segment segment); public void addBaseTimelineException(long domainValue); public void addBaseTimelineException(Date date); public void addBaseTimelineExclusions(long fromBaseDomainValue, long toBaseDomainValue); public long getExceptionSegmentCount(long fromMillisecond, long toMillisecond); public Segment getSegment(long millisecond); public Segment getSegment(Date date); private boolean equals(Object o, Object p); public boolean equals(Object o); public int hashCode(); private int binarySearchExceptionSegments(Segment segment); public long getTime(Date date); public Date getDate(long value); public Object clone() throws CloneNotSupportedException; protected Segment(); protected Segment(long millisecond); public long calculateSegmentNumber(long millis); public long getSegmentNumber(); public long getSegmentCount(); public long getSegmentStart(); public long getSegmentEnd(); public long getMillisecond(); public Date getDate(); public boolean contains(long millis); public boolean contains(long from, long to); public boolean contains(Segment segment); public boolean contained(long from, long to); public Segment intersect(long from, long to); public boolean before(Segment other); public boolean after(Segment other); public boolean equals(Object object); public Segment copy(); public int compareTo(Object object); public boolean inIncludeSegments(); public boolean inExcludeSegments(); private long getSegmentNumberRelativeToGroup(); public boolean inExceptionSegments(); public void inc(long n); public void inc(); public void dec(long n); public void dec(); public void moveIndexToStart(); public void moveIndexToEnd(); public SegmentRange(long fromMillisecond, long toMillisecond); public long getSegmentCount(); public Segment intersect(long from, long to); public boolean inIncludeSegments(); public boolean inExcludeSegments(); public void inc(long n); public BaseTimelineSegmentRange(long fromDomainValue, long toDomainValue);
348
testFifteenMinSegmentedTimeline
```java "2000-12-25", "2001-01-01", "2001-01-15", "2001-02-19", "2001-04-13", "2001-05-28", "2001-07-04", "2001-09-03", "2001-09-11", "2001-09-12", "2001-09-13", "2001-09-14", "2001-11-22", "2001-12-25", "2002-01-01", "2002-01-21", "2002-02-18", "2002-03-29", "2002-05-27", "2002-07-04", "2002-09-02", "2002-11-28", "2002-12-25"}; private static final String[] FIFTEEN_MIN_EXCEPTIONS = { "2000-01-10 09:00:00", "2000-01-10 09:15:00", "2000-01-10 09:30:00", "2000-01-10 09:45:00", "2000-01-10 10:00:00", "2000-01-10 10:15:00", "2000-02-15 09:00:00", "2000-02-15 09:15:00", "2000-02-15 09:30:00", "2000-02-15 09:45:00", "2000-02-15 10:00:00", "2000-02-15 10:15:00", "2000-02-16 11:00:00", "2000-02-16 11:15:00", "2000-02-16 11:30:00", "2000-02-16 11:45:00", "2000-02-16 12:00:00", "2000-02-16 12:15:00", "2000-02-16 12:30:00", "2000-02-16 12:45:00", "2000-02-16 01:00:00", "2000-02-16 01:15:00", "2000-02-16 01:30:00", "2000-02-16 01:45:00", "2000-05-17 11:45:00", "2000-05-17 12:00:00", "2000-05-17 12:15:00", "2000-05-17 12:30:00", "2000-05-17 12:45:00", "2000-05-17 01:00:00", "2000-05-17 01:15:00", "2000-05-17 01:30:00", "2000-05-17 01:45:00", "2000-05-17 02:00:00", "2000-05-17 02:15:00", "2000-05-17 02:30:00", "2000-05-17 02:45:00", "2000-05-17 03:00:00", "2000-05-17 03:15:00", "2000-05-17 03:30:00", "2000-05-17 03:45:00", "2000-05-17 04:00:00"}; private SegmentedTimeline msTimeline; private SegmentedTimeline ms2Timeline; private SegmentedTimeline ms2BaseTimeline; private SegmentedTimeline mondayFridayTimeline; private SegmentedTimeline fifteenMinTimeline; private Calendar monday; private Calendar monday9am; public static Test suite(); public SegmentedTimelineTests(String name); protected void setUp() throws Exception; protected void tearDown() throws Exception; public void testMsSegmentedTimeline(); public void testMs2SegmentedTimeline(); public void testMondayThroughFridaySegmentedTimeline(); public void testFifteenMinSegmentedTimeline(); public void testMsSegment(); public void testMs2Segment(); public void testMondayThroughFridaySegment(); public void testFifteenMinSegment(); public void verifyOneSegment(SegmentedTimeline timeline); public void testMsInc(); public void testMs2Inc(); public void testMondayThroughFridayInc(); public void testFifteenMinInc(); public void verifyInc(SegmentedTimeline timeline); public void testMsIncludedAndExcludedSegments(); public void testMs2IncludedAndExcludedSegments(); public void testMondayThroughFridayIncludedAndExcludedSegments(); public void testFifteenMinIncludedAndExcludedSegments(); public void verifyIncludedAndExcludedSegments(SegmentedTimeline timeline, long n); public void testMsExceptionSegments() throws ParseException; public void testMs2BaseTimelineExceptionSegments() throws ParseException; public void testMondayThoughFridayExceptionSegments() throws ParseException; public void testFifteenMinExceptionSegments() throws ParseException; public void verifyExceptionSegments(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException; public void testMsTranslations() throws ParseException; public void testMs2BaseTimelineTranslations() throws ParseException; public void testMs2Translations() throws ParseException; public void textMondayThroughFridayTranslations() throws ParseException; public void testFifteenMinTranslations() throws ParseException; public void verifyTranslations(SegmentedTimeline timeline, long startTest); public void testSerialization(); private void verifySerialization(SegmentedTimeline a1); private long[] verifyFillInExceptions(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException; private void fillInBaseTimelineExceptions(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException; private void fillInBaseTimelineExclusionsAsExceptions( SegmentedTimeline timeline, long from, long to); public void testCloning(); public void testEquals(); public void testHashCode(); public void testSerialization2(); public void testBasicSegmentedTimeline(); public void testSegmentedTimelineWithException1(); public static void main(String[] args) throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testFifteenMinSegmentedTimeline` for the `SegmentedTimeline` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests that the factory method that creates a 15-min 9:00 AM 4:00 PM * segmented axis does so correctly. */
340
// "2000-12-25", "2001-01-01", "2001-01-15", "2001-02-19", "2001-04-13", // "2001-05-28", "2001-07-04", "2001-09-03", "2001-09-11", "2001-09-12", // "2001-09-13", "2001-09-14", "2001-11-22", "2001-12-25", "2002-01-01", // "2002-01-21", "2002-02-18", "2002-03-29", "2002-05-27", "2002-07-04", // "2002-09-02", "2002-11-28", "2002-12-25"}; // private static final String[] FIFTEEN_MIN_EXCEPTIONS = { // "2000-01-10 09:00:00", "2000-01-10 09:15:00", "2000-01-10 09:30:00", // "2000-01-10 09:45:00", "2000-01-10 10:00:00", "2000-01-10 10:15:00", // "2000-02-15 09:00:00", "2000-02-15 09:15:00", "2000-02-15 09:30:00", // "2000-02-15 09:45:00", "2000-02-15 10:00:00", "2000-02-15 10:15:00", // "2000-02-16 11:00:00", "2000-02-16 11:15:00", "2000-02-16 11:30:00", // "2000-02-16 11:45:00", "2000-02-16 12:00:00", "2000-02-16 12:15:00", // "2000-02-16 12:30:00", "2000-02-16 12:45:00", "2000-02-16 01:00:00", // "2000-02-16 01:15:00", "2000-02-16 01:30:00", "2000-02-16 01:45:00", // "2000-05-17 11:45:00", "2000-05-17 12:00:00", "2000-05-17 12:15:00", // "2000-05-17 12:30:00", "2000-05-17 12:45:00", "2000-05-17 01:00:00", // "2000-05-17 01:15:00", "2000-05-17 01:30:00", "2000-05-17 01:45:00", // "2000-05-17 02:00:00", "2000-05-17 02:15:00", "2000-05-17 02:30:00", // "2000-05-17 02:45:00", "2000-05-17 03:00:00", "2000-05-17 03:15:00", // "2000-05-17 03:30:00", "2000-05-17 03:45:00", "2000-05-17 04:00:00"}; // private SegmentedTimeline msTimeline; // private SegmentedTimeline ms2Timeline; // private SegmentedTimeline ms2BaseTimeline; // private SegmentedTimeline mondayFridayTimeline; // private SegmentedTimeline fifteenMinTimeline; // private Calendar monday; // private Calendar monday9am; // // public static Test suite(); // public SegmentedTimelineTests(String name); // protected void setUp() throws Exception; // protected void tearDown() throws Exception; // public void testMsSegmentedTimeline(); // public void testMs2SegmentedTimeline(); // public void testMondayThroughFridaySegmentedTimeline(); // public void testFifteenMinSegmentedTimeline(); // public void testMsSegment(); // public void testMs2Segment(); // public void testMondayThroughFridaySegment(); // public void testFifteenMinSegment(); // public void verifyOneSegment(SegmentedTimeline timeline); // public void testMsInc(); // public void testMs2Inc(); // public void testMondayThroughFridayInc(); // public void testFifteenMinInc(); // public void verifyInc(SegmentedTimeline timeline); // public void testMsIncludedAndExcludedSegments(); // public void testMs2IncludedAndExcludedSegments(); // public void testMondayThroughFridayIncludedAndExcludedSegments(); // public void testFifteenMinIncludedAndExcludedSegments(); // public void verifyIncludedAndExcludedSegments(SegmentedTimeline timeline, // long n); // public void testMsExceptionSegments() throws ParseException; // public void testMs2BaseTimelineExceptionSegments() throws ParseException; // public void testMondayThoughFridayExceptionSegments() // throws ParseException; // public void testFifteenMinExceptionSegments() throws ParseException; // public void verifyExceptionSegments(SegmentedTimeline timeline, // String[] exceptionString, // Format fmt) // throws ParseException; // public void testMsTranslations() throws ParseException; // public void testMs2BaseTimelineTranslations() throws ParseException; // public void testMs2Translations() throws ParseException; // public void textMondayThroughFridayTranslations() throws ParseException; // public void testFifteenMinTranslations() throws ParseException; // public void verifyTranslations(SegmentedTimeline timeline, long startTest); // public void testSerialization(); // private void verifySerialization(SegmentedTimeline a1); // private long[] verifyFillInExceptions(SegmentedTimeline timeline, // String[] exceptionString, // Format fmt) throws ParseException; // private void fillInBaseTimelineExceptions(SegmentedTimeline timeline, // String[] exceptionString, // Format fmt) throws ParseException; // private void fillInBaseTimelineExclusionsAsExceptions( // SegmentedTimeline timeline, long from, long to); // public void testCloning(); // public void testEquals(); // public void testHashCode(); // public void testSerialization2(); // public void testBasicSegmentedTimeline(); // public void testSegmentedTimelineWithException1(); // public static void main(String[] args) throws Exception; // } // You are a professional Java test case writer, please create a test case named `testFifteenMinSegmentedTimeline` for the `SegmentedTimeline` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests that the factory method that creates a 15-min 9:00 AM 4:00 PM * segmented axis does so correctly. */ public void testFifteenMinSegmentedTimeline() {
/** * Tests that the factory method that creates a 15-min 9:00 AM 4:00 PM * segmented axis does so correctly. */
1
org.jfree.chart.axis.SegmentedTimeline
tests
```java "2000-12-25", "2001-01-01", "2001-01-15", "2001-02-19", "2001-04-13", "2001-05-28", "2001-07-04", "2001-09-03", "2001-09-11", "2001-09-12", "2001-09-13", "2001-09-14", "2001-11-22", "2001-12-25", "2002-01-01", "2002-01-21", "2002-02-18", "2002-03-29", "2002-05-27", "2002-07-04", "2002-09-02", "2002-11-28", "2002-12-25"}; private static final String[] FIFTEEN_MIN_EXCEPTIONS = { "2000-01-10 09:00:00", "2000-01-10 09:15:00", "2000-01-10 09:30:00", "2000-01-10 09:45:00", "2000-01-10 10:00:00", "2000-01-10 10:15:00", "2000-02-15 09:00:00", "2000-02-15 09:15:00", "2000-02-15 09:30:00", "2000-02-15 09:45:00", "2000-02-15 10:00:00", "2000-02-15 10:15:00", "2000-02-16 11:00:00", "2000-02-16 11:15:00", "2000-02-16 11:30:00", "2000-02-16 11:45:00", "2000-02-16 12:00:00", "2000-02-16 12:15:00", "2000-02-16 12:30:00", "2000-02-16 12:45:00", "2000-02-16 01:00:00", "2000-02-16 01:15:00", "2000-02-16 01:30:00", "2000-02-16 01:45:00", "2000-05-17 11:45:00", "2000-05-17 12:00:00", "2000-05-17 12:15:00", "2000-05-17 12:30:00", "2000-05-17 12:45:00", "2000-05-17 01:00:00", "2000-05-17 01:15:00", "2000-05-17 01:30:00", "2000-05-17 01:45:00", "2000-05-17 02:00:00", "2000-05-17 02:15:00", "2000-05-17 02:30:00", "2000-05-17 02:45:00", "2000-05-17 03:00:00", "2000-05-17 03:15:00", "2000-05-17 03:30:00", "2000-05-17 03:45:00", "2000-05-17 04:00:00"}; private SegmentedTimeline msTimeline; private SegmentedTimeline ms2Timeline; private SegmentedTimeline ms2BaseTimeline; private SegmentedTimeline mondayFridayTimeline; private SegmentedTimeline fifteenMinTimeline; private Calendar monday; private Calendar monday9am; public static Test suite(); public SegmentedTimelineTests(String name); protected void setUp() throws Exception; protected void tearDown() throws Exception; public void testMsSegmentedTimeline(); public void testMs2SegmentedTimeline(); public void testMondayThroughFridaySegmentedTimeline(); public void testFifteenMinSegmentedTimeline(); public void testMsSegment(); public void testMs2Segment(); public void testMondayThroughFridaySegment(); public void testFifteenMinSegment(); public void verifyOneSegment(SegmentedTimeline timeline); public void testMsInc(); public void testMs2Inc(); public void testMondayThroughFridayInc(); public void testFifteenMinInc(); public void verifyInc(SegmentedTimeline timeline); public void testMsIncludedAndExcludedSegments(); public void testMs2IncludedAndExcludedSegments(); public void testMondayThroughFridayIncludedAndExcludedSegments(); public void testFifteenMinIncludedAndExcludedSegments(); public void verifyIncludedAndExcludedSegments(SegmentedTimeline timeline, long n); public void testMsExceptionSegments() throws ParseException; public void testMs2BaseTimelineExceptionSegments() throws ParseException; public void testMondayThoughFridayExceptionSegments() throws ParseException; public void testFifteenMinExceptionSegments() throws ParseException; public void verifyExceptionSegments(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException; public void testMsTranslations() throws ParseException; public void testMs2BaseTimelineTranslations() throws ParseException; public void testMs2Translations() throws ParseException; public void textMondayThroughFridayTranslations() throws ParseException; public void testFifteenMinTranslations() throws ParseException; public void verifyTranslations(SegmentedTimeline timeline, long startTest); public void testSerialization(); private void verifySerialization(SegmentedTimeline a1); private long[] verifyFillInExceptions(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException; private void fillInBaseTimelineExceptions(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException; private void fillInBaseTimelineExclusionsAsExceptions( SegmentedTimeline timeline, long from, long to); public void testCloning(); public void testEquals(); public void testHashCode(); public void testSerialization2(); public void testBasicSegmentedTimeline(); public void testSegmentedTimelineWithException1(); public static void main(String[] args) throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testFifteenMinSegmentedTimeline` for the `SegmentedTimeline` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests that the factory method that creates a 15-min 9:00 AM 4:00 PM * segmented axis does so correctly. */ public void testFifteenMinSegmentedTimeline() { ```
public class SegmentedTimeline implements Timeline, Cloneable, Serializable
package org.jfree.chart.axis.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 java.text.Format; import java.text.NumberFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Iterator; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.axis.SegmentedTimeline;
public static Test suite(); public SegmentedTimelineTests(String name); protected void setUp() throws Exception; protected void tearDown() throws Exception; public void testMsSegmentedTimeline(); public void testMs2SegmentedTimeline(); public void testMondayThroughFridaySegmentedTimeline(); public void testFifteenMinSegmentedTimeline(); public void testMsSegment(); public void testMs2Segment(); public void testMondayThroughFridaySegment(); public void testFifteenMinSegment(); public void verifyOneSegment(SegmentedTimeline timeline); public void testMsInc(); public void testMs2Inc(); public void testMondayThroughFridayInc(); public void testFifteenMinInc(); public void verifyInc(SegmentedTimeline timeline); public void testMsIncludedAndExcludedSegments(); public void testMs2IncludedAndExcludedSegments(); public void testMondayThroughFridayIncludedAndExcludedSegments(); public void testFifteenMinIncludedAndExcludedSegments(); public void verifyIncludedAndExcludedSegments(SegmentedTimeline timeline, long n); public void testMsExceptionSegments() throws ParseException; public void testMs2BaseTimelineExceptionSegments() throws ParseException; public void testMondayThoughFridayExceptionSegments() throws ParseException; public void testFifteenMinExceptionSegments() throws ParseException; public void verifyExceptionSegments(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException; public void testMsTranslations() throws ParseException; public void testMs2BaseTimelineTranslations() throws ParseException; public void testMs2Translations() throws ParseException; public void textMondayThroughFridayTranslations() throws ParseException; public void testFifteenMinTranslations() throws ParseException; public void verifyTranslations(SegmentedTimeline timeline, long startTest); public void testSerialization(); private void verifySerialization(SegmentedTimeline a1); private long[] verifyFillInExceptions(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException; private void fillInBaseTimelineExceptions(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException; private void fillInBaseTimelineExclusionsAsExceptions( SegmentedTimeline timeline, long from, long to); public void testCloning(); public void testEquals(); public void testHashCode(); public void testSerialization2(); public void testBasicSegmentedTimeline(); public void testSegmentedTimelineWithException1(); public static void main(String[] args) throws Exception;
14576b2f5539d56a91243e003b1fcd7a08b0e68b102633cc35665aaf8189ae49
[ "org.jfree.chart.axis.junit.SegmentedTimelineTests::testFifteenMinSegmentedTimeline" ]
private static final long serialVersionUID = 1093779862539903110L; public static final long DAY_SEGMENT_SIZE = 24 * 60 * 60 * 1000; public static final long HOUR_SEGMENT_SIZE = 60 * 60 * 1000; public static final long FIFTEEN_MINUTE_SEGMENT_SIZE = 15 * 60 * 1000; public static final long MINUTE_SEGMENT_SIZE = 60 * 1000; public static long FIRST_MONDAY_AFTER_1900; public static TimeZone NO_DST_TIME_ZONE; public static TimeZone DEFAULT_TIME_ZONE = TimeZone.getDefault(); private Calendar workingCalendarNoDST; private Calendar workingCalendar = Calendar.getInstance(); private long segmentSize; private int segmentsIncluded; private int segmentsExcluded; private int groupSegmentCount; private long startTime; private long segmentsIncludedSize; private long segmentsExcludedSize; private long segmentsGroupSize; private List exceptionSegments = new ArrayList(); private SegmentedTimeline baseTimeline; private boolean adjustForDaylightSaving = false;
public void testFifteenMinSegmentedTimeline()
private static final int TEST_CYCLE_START = 0; private static final int TEST_CYCLE_END = 1000; private static final int TEST_CYCLE_INC = 55; private static final long FIVE_YEARS = 5 * 365 * SegmentedTimeline.DAY_SEGMENT_SIZE; private static final NumberFormat NUMBER_FORMAT = NumberFormat.getNumberInstance(); private static final SimpleDateFormat DATE_FORMAT; private static final SimpleDateFormat DATE_TIME_FORMAT; private static final String[] MS_EXCEPTIONS = {"0", "2", "4", "10", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "47", "58", "100", "101"}; private static final String[] MS2_BASE_TIMELINE_EXCEPTIONS = {"0", "8", "16", "24", "32", "40", "48", "56", "64", "72", "80", "88", "96", "104", "112", "120", "128", "136"}; private static final String[] US_HOLIDAYS = {"2000-01-17", "2000-02-21", "2000-04-21", "2000-05-29", "2000-07-04", "2000-09-04", "2000-11-23", "2000-12-25", "2001-01-01", "2001-01-15", "2001-02-19", "2001-04-13", "2001-05-28", "2001-07-04", "2001-09-03", "2001-09-11", "2001-09-12", "2001-09-13", "2001-09-14", "2001-11-22", "2001-12-25", "2002-01-01", "2002-01-21", "2002-02-18", "2002-03-29", "2002-05-27", "2002-07-04", "2002-09-02", "2002-11-28", "2002-12-25"}; private static final String[] FIFTEEN_MIN_EXCEPTIONS = { "2000-01-10 09:00:00", "2000-01-10 09:15:00", "2000-01-10 09:30:00", "2000-01-10 09:45:00", "2000-01-10 10:00:00", "2000-01-10 10:15:00", "2000-02-15 09:00:00", "2000-02-15 09:15:00", "2000-02-15 09:30:00", "2000-02-15 09:45:00", "2000-02-15 10:00:00", "2000-02-15 10:15:00", "2000-02-16 11:00:00", "2000-02-16 11:15:00", "2000-02-16 11:30:00", "2000-02-16 11:45:00", "2000-02-16 12:00:00", "2000-02-16 12:15:00", "2000-02-16 12:30:00", "2000-02-16 12:45:00", "2000-02-16 01:00:00", "2000-02-16 01:15:00", "2000-02-16 01:30:00", "2000-02-16 01:45:00", "2000-05-17 11:45:00", "2000-05-17 12:00:00", "2000-05-17 12:15:00", "2000-05-17 12:30:00", "2000-05-17 12:45:00", "2000-05-17 01:00:00", "2000-05-17 01:15:00", "2000-05-17 01:30:00", "2000-05-17 01:45:00", "2000-05-17 02:00:00", "2000-05-17 02:15:00", "2000-05-17 02:30:00", "2000-05-17 02:45:00", "2000-05-17 03:00:00", "2000-05-17 03:15:00", "2000-05-17 03:30:00", "2000-05-17 03:45:00", "2000-05-17 04:00:00"}; private SegmentedTimeline msTimeline; private SegmentedTimeline ms2Timeline; private SegmentedTimeline ms2BaseTimeline; private SegmentedTimeline mondayFridayTimeline; private SegmentedTimeline fifteenMinTimeline; private Calendar monday; private Calendar monday9am;
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.] * * ---------------------------- * SegmentedTimelineTests.java * ---------------------------- * (C) Copyright 2003-2008, by Bill Kelemen and Contributors. * * Original Author: Bill Kelemen; * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes * ------- * 24-May-2003 : Version 1 (BK); * 07-Jan-2005 : Added test for hashCode() method (DG); * 02-Feb-2007 : Removed author tags all over JFreeChart sources (DG); * */ package org.jfree.chart.axis.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 java.text.Format; import java.text.NumberFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Iterator; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.axis.SegmentedTimeline; /** * JUnit Tests for the {@link SegmentedTimeline} class. */ public class SegmentedTimelineTests extends TestCase { /** These constants control test cycles in the validateXXXX methods. */ private static final int TEST_CYCLE_START = 0; /** These constants control test cycles in the validateXXXX methods. */ private static final int TEST_CYCLE_END = 1000; /** These constants control test cycles in the validateXXXX methods. */ private static final int TEST_CYCLE_INC = 55; /** Number of ms in five years */ private static final long FIVE_YEARS = 5 * 365 * SegmentedTimeline.DAY_SEGMENT_SIZE; /** Number format object for ms tests. */ private static final NumberFormat NUMBER_FORMAT = NumberFormat.getNumberInstance(); /** Date format object for Monday through Friday tests. */ private static final SimpleDateFormat DATE_FORMAT; /** Date format object 9:00 AM to 4:00 PM tests. */ private static final SimpleDateFormat DATE_TIME_FORMAT; /** Some ms exceptions for ms testing. */ private static final String[] MS_EXCEPTIONS = {"0", "2", "4", "10", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "47", "58", "100", "101"}; /** Some ms4 exceptions for ms testing. */ private static final String[] MS2_BASE_TIMELINE_EXCEPTIONS = {"0", "8", "16", "24", "32", "40", "48", "56", "64", "72", "80", "88", "96", "104", "112", "120", "128", "136"}; /** US non-trading dates in 2000 through 2002 to test exceptions. */ private static final String[] US_HOLIDAYS = {"2000-01-17", "2000-02-21", "2000-04-21", "2000-05-29", "2000-07-04", "2000-09-04", "2000-11-23", "2000-12-25", "2001-01-01", "2001-01-15", "2001-02-19", "2001-04-13", "2001-05-28", "2001-07-04", "2001-09-03", "2001-09-11", "2001-09-12", "2001-09-13", "2001-09-14", "2001-11-22", "2001-12-25", "2002-01-01", "2002-01-21", "2002-02-18", "2002-03-29", "2002-05-27", "2002-07-04", "2002-09-02", "2002-11-28", "2002-12-25"}; /** Some test exceptions for the fifteen min timeline. */ private static final String[] FIFTEEN_MIN_EXCEPTIONS = { "2000-01-10 09:00:00", "2000-01-10 09:15:00", "2000-01-10 09:30:00", "2000-01-10 09:45:00", "2000-01-10 10:00:00", "2000-01-10 10:15:00", "2000-02-15 09:00:00", "2000-02-15 09:15:00", "2000-02-15 09:30:00", "2000-02-15 09:45:00", "2000-02-15 10:00:00", "2000-02-15 10:15:00", "2000-02-16 11:00:00", "2000-02-16 11:15:00", "2000-02-16 11:30:00", "2000-02-16 11:45:00", "2000-02-16 12:00:00", "2000-02-16 12:15:00", "2000-02-16 12:30:00", "2000-02-16 12:45:00", "2000-02-16 01:00:00", "2000-02-16 01:15:00", "2000-02-16 01:30:00", "2000-02-16 01:45:00", "2000-05-17 11:45:00", "2000-05-17 12:00:00", "2000-05-17 12:15:00", "2000-05-17 12:30:00", "2000-05-17 12:45:00", "2000-05-17 01:00:00", "2000-05-17 01:15:00", "2000-05-17 01:30:00", "2000-05-17 01:45:00", "2000-05-17 02:00:00", "2000-05-17 02:15:00", "2000-05-17 02:30:00", "2000-05-17 02:45:00", "2000-05-17 03:00:00", "2000-05-17 03:15:00", "2000-05-17 03:30:00", "2000-05-17 03:45:00", "2000-05-17 04:00:00"}; /** Our 1-ms test timeline using 5 included and 2 excluded segments. */ private SegmentedTimeline msTimeline; /** * Our 1-ms test timeline (with baseTimeline) using 2 included and 2 * excluded segments. */ private SegmentedTimeline ms2Timeline; /** * Our 4-ms test base timeline for ms2Timeline using 1 included and 1 * excluded segments */ private SegmentedTimeline ms2BaseTimeline; /** Our test Monday through Friday test timeline. */ private SegmentedTimeline mondayFridayTimeline; /** Our 9:00 AM to 4:00 PM fifteen minute timeline. */ private SegmentedTimeline fifteenMinTimeline; /** ms from 1970-01-01 to first monday after 2001-01-01. */ private Calendar monday; /** ms from 1970-01-01 to 9 am first monday after 2001-01-01. */ private Calendar monday9am; /** Static initialization block. */ static { DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); DATE_FORMAT.setTimeZone(SegmentedTimeline.NO_DST_TIME_ZONE); DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); DATE_TIME_FORMAT.setTimeZone(SegmentedTimeline.NO_DST_TIME_ZONE); } /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(SegmentedTimelineTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public SegmentedTimelineTests(String name) { super(name); } /** * Sets up the fixture, for example, open a network connection. * This method is called before a test is executed. * * @throws Exception if there is a problem. */ protected void setUp() throws Exception { // setup our test timelines // // Legend for comments below: // <spaces> = Segments included in the final timeline // EE = Excluded segments via timeline rules // xx = Exception segments inherited from base timeline exclusions // 1-ms test timeline using 5 included and 2 excluded segments. // // timeline start time = 0 // | // v // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 .. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+.. // | | | | | |EE|EE| | | | | |EE|EE| | | | | | |EE|EE| <-- msTimeline // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+.. // \_________ ________/ \_/ // \/ | // segment group segment size = 1 ms // this.msTimeline = new SegmentedTimeline(1, 5, 2); this.msTimeline.setStartTime(0); // 4-ms test base timeline for ms2Timeline using 1 included and 1 // excluded segments // // timeline start time = 0 // | // v // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ... // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+... // | | | | |EE|EE|EE|EE| | | | |EE|EE|EE|EE| | | | | <-- ms2BaseTimeline // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+... // \__________ _________/ \____ _____/ // \/ \/ // segment group segment size = 4 ms // this.ms2BaseTimeline = new SegmentedTimeline(4, 1, 1); this.ms2BaseTimeline.setStartTime(0); // 1-ms test timeline (with a baseTimeline) using 2 included and 2 // excluded segments centered inside each base segment // // The ms2Timeline without a base would look like this: // // timeline start time = 1 // | // v // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ... // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+... // |EE| | |EE|EE| | |EE|EE| | |EE|EE| | |EE|EE| | |EE| <-- ms2Timeline // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+... // \____ _____/ \_/ // \/ | // segment group segment size = 1 ms // // With the base timeline some originally included segments are now // removed (see "xx" below): // // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ... // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+... // |EE| | |EE|EE|xx|xx|EE|EE| | |EE|EE|xx|xx|EE|EE| | |EE| <-- ms2Timeline // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+... // | | | | |EE|EE|EE|EE| | | | |EE|EE|EE|EE| | | | | <-- ms2BaseTimeline // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+... // this.ms2Timeline = new SegmentedTimeline(1, 2, 2); this.ms2Timeline.setStartTime(1); this.ms2Timeline.setBaseTimeline(this.ms2BaseTimeline); // test monday though friday timeline this.mondayFridayTimeline = SegmentedTimeline.newMondayThroughFridayTimeline(); // test 9am-4pm Monday through Friday timeline this.fifteenMinTimeline = SegmentedTimeline.newFifteenMinuteTimeline(); // find first Monday after 2001-01-01 Calendar cal = new GregorianCalendar( SegmentedTimeline.NO_DST_TIME_ZONE); cal.set(2001, 0, 1, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) { cal.add(Calendar.DATE, 1); } this.monday = (Calendar) cal.clone(); // calculate 9am on the first Monday after 2001-01-01 cal.add(Calendar.HOUR, 9); this.monday9am = (Calendar) cal.clone(); } /** * Tears down the fixture, for example, close a network connection. * This method is called after a test is executed. * * @throws Exception if there is a problem. */ protected void tearDown() throws Exception { // does nothing } ////////////////////////////////////////////////////////////////////////// // test construction process ////////////////////////////////////////////////////////////////////////// /** * Tests that the new method that created the msTimeline segmented * timeline did so correctly. */ public void testMsSegmentedTimeline() { // verify attributes set during object construction assertEquals(1, this.msTimeline.getSegmentSize()); assertEquals(0, this.msTimeline.getStartTime()); assertEquals(5, this.msTimeline.getSegmentsIncluded()); assertEquals(2, this.msTimeline.getSegmentsExcluded()); } /** * Tests that the new method that created the ms2Timeline segmented * timeline did so correctly. */ public void testMs2SegmentedTimeline() { // verify attributes set during object construction assertEquals(1, this.ms2Timeline.getSegmentSize()); assertEquals(1, this.ms2Timeline.getStartTime()); assertEquals(2, this.ms2Timeline.getSegmentsIncluded()); assertEquals(2, this.ms2Timeline.getSegmentsExcluded()); assertEquals(this.ms2BaseTimeline, this.ms2Timeline.getBaseTimeline()); } /** * Tests that the factory method that creates Monday through Friday * segmented timeline does so correctly. */ public void testMondayThroughFridaySegmentedTimeline() { // verify attributes set during object construction assertEquals(SegmentedTimeline.DAY_SEGMENT_SIZE, this.mondayFridayTimeline.getSegmentSize()); assertEquals(SegmentedTimeline.FIRST_MONDAY_AFTER_1900, this.mondayFridayTimeline.getStartTime()); assertEquals(5, this.mondayFridayTimeline.getSegmentsIncluded()); assertEquals(2, this.mondayFridayTimeline.getSegmentsExcluded()); } /** * Tests that the factory method that creates a 15-min 9:00 AM 4:00 PM * segmented axis does so correctly. */ public void testFifteenMinSegmentedTimeline() { assertEquals(SegmentedTimeline.FIFTEEN_MINUTE_SEGMENT_SIZE, this.fifteenMinTimeline.getSegmentSize()); assertEquals(SegmentedTimeline.FIRST_MONDAY_AFTER_1900 + 36 * this.fifteenMinTimeline.getSegmentSize(), this.fifteenMinTimeline.getStartTime()); assertEquals(28, this.fifteenMinTimeline.getSegmentsIncluded()); assertEquals(68, this.fifteenMinTimeline.getSegmentsExcluded()); } ////////////////////////////////////////////////////////////////////////// // test one-segment and adjacent segments ////////////////////////////////////////////////////////////////////////// /** * Tests one segment of the ms timeline. Internal indices * inside one segment as well as adjacent segments are verified. */ public void testMsSegment() { verifyOneSegment(this.msTimeline); } /** * Tests one segment of the ms timeline. Internal indices * inside one segment as well as adjacent segments are verified. */ public void testMs2Segment() { verifyOneSegment(this.ms2Timeline); } /** * Tests one segment of the Monday through Friday timeline. Internal indices * inside one segment as well as adjacent segments are verified. */ public void testMondayThroughFridaySegment() { verifyOneSegment(this.mondayFridayTimeline); } /** * Tests one segment of the Fifteen timeline. Internal indices * inside one segment as well as adjacent segments are verified. */ public void testFifteenMinSegment() { verifyOneSegment(this.fifteenMinTimeline); } /** * Tests one segment of the Monday through Friday timeline. Internal indices * inside one segment as well as adjacent segments are verified. * @param timeline the timeline to use for verifications. */ public void verifyOneSegment(SegmentedTimeline timeline) { for (long testCycle = TEST_CYCLE_START; testCycle < TEST_CYCLE_END; testCycle += TEST_CYCLE_INC) { // get two consecutive segments for various tests SegmentedTimeline.Segment segment1 = timeline.getSegment( this.monday.getTime().getTime() + testCycle); SegmentedTimeline.Segment segment2 = timeline.getSegment( segment1.getSegmentEnd() + 1); // verify segments are consecutive and correct assertEquals(segment1.getSegmentNumber() + 1, segment2.getSegmentNumber()); assertEquals(segment1.getSegmentEnd() + 1, segment2.getSegmentStart()); assertEquals(segment1.getSegmentStart() + timeline.getSegmentSize() - 1, segment1.getSegmentEnd()); assertEquals(segment1.getSegmentStart() + timeline.getSegmentSize(), segment2.getSegmentStart()); assertEquals(segment1.getSegmentEnd() + timeline.getSegmentSize(), segment2.getSegmentEnd()); // verify various indices inside a segment are the same segment long delta; if (timeline.getSegmentSize() > 1000000) { delta = timeline.getSegmentSize() / 10000; } else if (timeline.getSegmentSize() > 100000) { delta = timeline.getSegmentSize() / 1000; } else if (timeline.getSegmentSize() > 10000) { delta = timeline.getSegmentSize() / 100; } else if (timeline.getSegmentSize() > 1000) { delta = timeline.getSegmentSize() / 10; } else if (timeline.getSegmentSize() > 100) { delta = timeline.getSegmentSize() / 5; } else { delta = 1; } long start = segment1.getSegmentStart() + delta; long end = segment1.getSegmentStart() + timeline.getSegmentSize() - 1; SegmentedTimeline.Segment lastSeg = timeline.getSegment( segment1.getSegmentStart()); SegmentedTimeline.Segment seg; for (long i = start; i < end; i += delta) { seg = timeline.getSegment(i); assertEquals(lastSeg.getSegmentNumber(), seg.getSegmentNumber()); assertEquals(lastSeg.getSegmentStart(), seg.getSegmentStart()); assertEquals(lastSeg.getSegmentEnd(), seg.getSegmentEnd()); assertTrue(lastSeg.getMillisecond() < seg.getMillisecond()); lastSeg = seg; } // try next segment seg = timeline.getSegment(end + 1); assertEquals(segment2.getSegmentNumber(), seg.getSegmentNumber()); assertEquals(segment2.getSegmentStart(), seg.getSegmentStart()); assertEquals(segment2.getSegmentEnd(), seg.getSegmentEnd()); } } ////////////////////////////////////////////////////////////////////////// // test inc methods ////////////////////////////////////////////////////////////////////////// /** * Tests the inc methods on the msTimeline. */ public void testMsInc() { verifyInc(this.msTimeline); } /** * Tests the inc methods on the msTimeline. */ public void testMs2Inc() { verifyInc(this.ms2Timeline); } /** * Tests the inc methods on the Monday through Friday timeline. */ public void testMondayThroughFridayInc() { verifyInc(this.mondayFridayTimeline); } /** * Tests the inc methods on the Fifteen minute timeline. */ public void testFifteenMinInc() { verifyInc(this.fifteenMinTimeline); } /** * Tests the inc methods. * @param timeline the timeline to use for verifications. */ public void verifyInc(SegmentedTimeline timeline) { for (long testCycle = TEST_CYCLE_START; testCycle < TEST_CYCLE_END; testCycle += TEST_CYCLE_INC) { long m = timeline.getSegmentSize(); SegmentedTimeline.Segment segment = timeline.getSegment(testCycle); SegmentedTimeline.Segment seg1 = segment.copy(); for (int i = 0; i < 1000; i++) { // test inc() method SegmentedTimeline.Segment seg2 = seg1.copy(); seg2.inc(); if ((seg1.getSegmentEnd() + 1) != seg2.getSegmentStart()) { // logically consecutive segments non-physically consecutive // (with non-contained time in between) assertTrue(!timeline.containsDomainRange( seg1.getSegmentEnd() + 1, seg2.getSegmentStart() - 1)); assertEquals(0, (seg2.getSegmentStart() - seg1.getSegmentStart()) % m); assertEquals(0, (seg2.getSegmentEnd() - seg1.getSegmentEnd()) % m); assertEquals(0, (seg2.getMillisecond() - seg1.getMillisecond()) % m); } else { // physically consecutive assertEquals(seg1.getSegmentStart() + m, seg2.getSegmentStart()); assertEquals(seg1.getSegmentEnd() + m, seg2.getSegmentEnd()); assertEquals(seg1.getMillisecond() + m, seg2.getMillisecond()); } // test inc(n) method SegmentedTimeline.Segment seg3 = seg1.copy(); SegmentedTimeline.Segment seg4 = seg1.copy(); for (int j = 0; j < i; j++) { seg3.inc(); } seg4.inc(i); assertEquals(seg3.getSegmentStart(), seg4.getSegmentStart()); assertEquals(seg3.getSegmentEnd(), seg4.getSegmentEnd()); assertEquals(seg3.getMillisecond(), seg4.getMillisecond()); // go to another segment to continue test seg1.inc(); } } } ////////////////////////////////////////////////////////////////////////// // main include and excluded segments ////////////////////////////////////////////////////////////////////////// /** * Tests that the msTimeline's included and excluded * segments are being calculated correctly. */ public void testMsIncludedAndExcludedSegments() { verifyIncludedAndExcludedSegments(this.msTimeline, 0); } /** * Tests that the ms2Timeline's included and excluded * segments are being calculated correctly. */ public void testMs2IncludedAndExcludedSegments() { verifyIncludedAndExcludedSegments(this.ms2Timeline, 1); } /** * Tests that the Monday through Friday timeline's included and excluded * segments are being calculated correctly. The test is performed starting * on the first monday after 1/1/2000 and for five years. */ public void testMondayThroughFridayIncludedAndExcludedSegments() { verifyIncludedAndExcludedSegments(this.mondayFridayTimeline, this.monday.getTime().getTime()); } /** * Tests that the Fifteen-Min timeline's included and excluded * segments are being calculated correctly. The test is performed starting * on the first monday after 1/1/2000 and for five years. */ public void testFifteenMinIncludedAndExcludedSegments() { verifyIncludedAndExcludedSegments(this.fifteenMinTimeline, this.monday9am.getTime().getTime()); } /** * Tests that a timeline's included and excluded segments are being * calculated correctly. * * @param timeline the timeline to verify * @param n the first segment number to start verifying */ public void verifyIncludedAndExcludedSegments(SegmentedTimeline timeline, long n) { // clear any exceptions in this timeline timeline.setExceptionSegments(new java.util.ArrayList()); // test some included and excluded segments SegmentedTimeline.Segment segment = timeline.getSegment(n); for (int i = 0; i < 1000; i++) { int d = (i % timeline.getGroupSegmentCount()); if (d < timeline.getSegmentsIncluded()) { // should be an included segment assertTrue(segment.inIncludeSegments()); assertTrue(!segment.inExcludeSegments()); assertTrue(!segment.inExceptionSegments()); } else { // should be an excluded segment assertTrue(!segment.inIncludeSegments()); assertTrue(segment.inExcludeSegments()); assertTrue(!segment.inExceptionSegments()); } segment.inc(); } } ////////////////////////////////////////////////////////////////////////// // test exception segments ////////////////////////////////////////////////////////////////////////// /** * Tests methods related to exceptions methods in the msTimeline. * * @throws ParseException if there is a parsing error. */ public void testMsExceptionSegments() throws ParseException { verifyExceptionSegments(this.msTimeline, MS_EXCEPTIONS, NUMBER_FORMAT); } /** * Tests methods related to exceptions methods in the ms2BaseTimeline. * * @throws ParseException if there is a parsing error. */ public void testMs2BaseTimelineExceptionSegments() throws ParseException { verifyExceptionSegments(this.ms2BaseTimeline, MS2_BASE_TIMELINE_EXCEPTIONS, NUMBER_FORMAT); } /** * Tests methods related to exceptions methods in the mondayFridayTimeline. * * @throws ParseException if there is a parsing error. */ public void testMondayThoughFridayExceptionSegments() throws ParseException { verifyExceptionSegments(this.mondayFridayTimeline, US_HOLIDAYS, DATE_FORMAT); } /** * Tests methods related to exceptions methods in the fifteenMinTimeline. * * @throws ParseException if there is a parsing error. */ public void testFifteenMinExceptionSegments() throws ParseException { verifyExceptionSegments(this.fifteenMinTimeline, FIFTEEN_MIN_EXCEPTIONS, DATE_TIME_FORMAT); } /** * Tests methods related to adding exceptions. * * @param timeline the timeline to verify * @param exceptionString array of Strings that represent the exceptions * @param fmt Format object that can parse the exceptionString strings * * @throws ParseException if there is a parsing error. */ public void verifyExceptionSegments(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException { // fill in the exceptions long[] exception = verifyFillInExceptions(timeline, exceptionString, fmt); int m = exception.length; // verify list of exceptions assertEquals(exception.length, timeline.getExceptionSegments().size()); SegmentedTimeline.Segment lastSegment = timeline.getSegment( exception[m - 1]); for (int i = 0; i < m; i++) { SegmentedTimeline.Segment segment = timeline.getSegment( exception[i]); assertTrue(segment.inExceptionSegments()); // include current exception and last one assertEquals(m - i, timeline.getExceptionSegmentCount( segment.getSegmentStart(), lastSegment.getSegmentEnd())); // exclude current exception and last one assertEquals(Math.max(0, m - i - 2), timeline.getExceptionSegmentCount(exception[i] + 1, exception[m - 1] - 1)); } } ////////////////////////////////////////////////////////////////////////// // test timeline translations ////////////////////////////////////////////////////////////////////////// /** * Tests translations for 1-ms timeline * * @throws ParseException if there is a parsing error. */ public void testMsTranslations() throws ParseException { verifyFillInExceptions(this.msTimeline, MS_EXCEPTIONS, NUMBER_FORMAT); verifyTranslations(this.msTimeline, 0); } /** * Tests translations for the base timeline used for the ms2Timeline * * @throws ParseException if there is a parsing error. */ public void testMs2BaseTimelineTranslations() throws ParseException { verifyFillInExceptions(this.ms2BaseTimeline, MS2_BASE_TIMELINE_EXCEPTIONS, NUMBER_FORMAT); verifyTranslations(this.ms2BaseTimeline, 0); } /** * Tests translations for the Monday through Friday timeline * * @throws ParseException if there is a parsing error. */ public void testMs2Translations() throws ParseException { fillInBaseTimelineExceptions(this.ms2Timeline, MS2_BASE_TIMELINE_EXCEPTIONS, NUMBER_FORMAT); fillInBaseTimelineExclusionsAsExceptions(this.ms2Timeline, 0, 5000); verifyTranslations(this.ms2Timeline, 1); } /** * Tests translations for the Monday through Friday timeline * * @throws ParseException if there is a parsing error. */ public void textMondayThroughFridayTranslations() throws ParseException { verifyFillInExceptions(this.mondayFridayTimeline, US_HOLIDAYS, DATE_FORMAT); verifyTranslations(this.mondayFridayTimeline, this.monday.getTime().getTime()); } /** * Tests translations for the Fifteen Min timeline * * @throws ParseException if there is a parsing error. */ public void testFifteenMinTranslations() throws ParseException { verifyFillInExceptions(this.fifteenMinTimeline, FIFTEEN_MIN_EXCEPTIONS, DATE_TIME_FORMAT); fillInBaseTimelineExceptions(this.fifteenMinTimeline, US_HOLIDAYS, DATE_FORMAT); fillInBaseTimelineExclusionsAsExceptions(this.fifteenMinTimeline, this.monday9am.getTime().getTime(), this.monday9am.getTime().getTime() + FIVE_YEARS); verifyTranslations(this.fifteenMinTimeline, this.monday9am.getTime().getTime()); } /** * Tests translations between timelines. * * @param timeline the timeline to use for verifications. * @param startTest ??. */ public void verifyTranslations(SegmentedTimeline timeline, long startTest) { for (long testCycle = TEST_CYCLE_START; testCycle < TEST_CYCLE_END; testCycle += TEST_CYCLE_INC) { long millisecond = startTest + testCycle * timeline.getSegmentSize(); SegmentedTimeline.Segment segment = timeline.getSegment( millisecond); for (int i = 0; i < 1000; i++) { long translatedValue = timeline.toTimelineValue( segment.getMillisecond()); long newValue = timeline.toMillisecond(translatedValue); if (segment.inExcludeSegments() || segment.inExceptionSegments()) { // the reverse transformed value will be in the start of the // next non-excluded and non-exception segment SegmentedTimeline.Segment tempSegment = segment.copy(); tempSegment.moveIndexToStart(); do { tempSegment.inc(); } while (!tempSegment.inIncludeSegments()); assertEquals(tempSegment.getMillisecond(), newValue); } else { assertEquals(segment.getMillisecond(), newValue); } segment.inc(); } } } ////////////////////////////////////////////////////////////////////////// // test serialization ////////////////////////////////////////////////////////////////////////// /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { verifySerialization(this.msTimeline); verifySerialization(this.ms2Timeline); verifySerialization(this.ms2BaseTimeline); verifySerialization(SegmentedTimeline.newMondayThroughFridayTimeline()); verifySerialization(SegmentedTimeline.newFifteenMinuteTimeline()); } /** * Tests serialization of an instance. * @param a1 The timeline to verify the serialization */ private void verifySerialization(SegmentedTimeline a1) { SegmentedTimeline 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 = (SegmentedTimeline) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(a1, a2); } /** * Adds an array of exceptions to the timeline. The timeline exception list * is first cleared. * @param timeline The timeline where the exceptions will be stored * @param exceptionString The exceptions to load * @param fmt The date formatter to use to parse each exceptions[i] value * @throws ParseException If there is any exception parsing each * exceptions[i] value. * @return An array of Dates[] containing each exception date. */ private long[] verifyFillInExceptions(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException { // make sure there are no exceptions timeline.setExceptionSegments(new java.util.ArrayList()); assertEquals(0, timeline.getExceptionSegments().size()); // add our exceptions and store locally in ArrayList of Longs ArrayList exceptionList = new ArrayList(); for (int i = 0; i < exceptionString.length; i++) { long e; if (fmt instanceof NumberFormat) { e = ((NumberFormat) fmt).parse(exceptionString[i]).longValue(); } else { e = timeline.getTime(((SimpleDateFormat) fmt) .parse(exceptionString[i])); } // only add an exception if it is currently an included segment SegmentedTimeline.Segment segment = timeline.getSegment(e); if (segment.inIncludeSegments()) { timeline.addException(e); exceptionList.add(new Long(e)); assertEquals(exceptionList.size(), timeline.getExceptionSegments().size()); assertTrue(segment.inExceptionSegments()); } } // make array of exceptions long[] exception = new long[exceptionList.size()]; int i = 0; for (Iterator iter = exceptionList.iterator(); iter.hasNext();) { Long l = (Long) iter.next(); exception[i++] = l.longValue(); } return (exception); } /** * Adds an array of exceptions relative to the base timeline. * * @param timeline The timeline where the exceptions will be stored * @param exceptionString The exceptions to load * @param fmt The date formatter to use to parse each exceptions[i] value * @throws ParseException If there is any exception parsing each * exceptions[i] value. */ private void fillInBaseTimelineExceptions(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException { SegmentedTimeline baseTimeline = timeline.getBaseTimeline(); for (int i = 0; i < exceptionString.length; i++) { long e; if (fmt instanceof NumberFormat) { e = ((NumberFormat) fmt).parse(exceptionString[i]).longValue(); } else { e = timeline.getTime(((SimpleDateFormat) fmt) .parse(exceptionString[i])); } timeline.addBaseTimelineException(e); // verify all timeline segments included in the // baseTimeline.segment are now exceptions SegmentedTimeline.Segment segment1 = baseTimeline.getSegment(e); for (SegmentedTimeline.Segment segment2 = timeline.getSegment(segment1.getSegmentStart()); segment2.getSegmentStart() <= segment1.getSegmentEnd(); segment2.inc()) { if (!segment2.inExcludeSegments()) { assertTrue(segment2.inExceptionSegments()); } } } } /** * Adds new exceptions to a timeline. The exceptions are the excluded * segments from its base timeline. * * @param timeline the timeline. * @param from the start. * @param to the end. */ private void fillInBaseTimelineExclusionsAsExceptions( SegmentedTimeline timeline, long from, long to) { // add the base timeline exclusions as timeline's esceptions timeline.addBaseTimelineExclusions(from, to); // validate base timeline exclusions added as timeline's esceptions for (SegmentedTimeline.Segment segment1 = timeline.getBaseTimeline() .getSegment(from); segment1.getSegmentStart() <= to; segment1.inc()) { if (segment1.inExcludeSegments()) { // verify all timeline segments included in the // baseTimeline.segment are now exceptions for (SegmentedTimeline.Segment segment2 = timeline.getSegment( segment1.getSegmentStart()); segment2.getSegmentStart() <= segment1.getSegmentEnd(); segment2.inc()) { if (!segment2.inExcludeSegments()) { assertTrue(segment2.inExceptionSegments()); } } } } } /** * Confirm that cloning works. */ public void testCloning() { SegmentedTimeline l1 = new SegmentedTimeline(1000, 5, 2); SegmentedTimeline l2 = null; try { l2 = (SegmentedTimeline) l1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(l1 != l2); assertTrue(l1.getClass() == l2.getClass()); assertTrue(l1.equals(l2)); } /** * Confirm that the equals method can distinguish all the required fields. */ public void testEquals() { SegmentedTimeline l1 = new SegmentedTimeline(1000, 5, 2); SegmentedTimeline l2 = new SegmentedTimeline(1000, 5, 2); assertTrue(l1.equals(l2)); l1 = new SegmentedTimeline(1000, 5, 2); l2 = new SegmentedTimeline(1001, 5, 2); assertFalse(l1.equals(l2)); l1 = new SegmentedTimeline(1000, 5, 2); l2 = new SegmentedTimeline(1000, 4, 2); assertFalse(l1.equals(l2)); l1 = new SegmentedTimeline(1000, 5, 2); l2 = new SegmentedTimeline(1000, 5, 1); assertFalse(l1.equals(l2)); l1 = new SegmentedTimeline(1000, 5, 2); l2 = new SegmentedTimeline(1000, 5, 2); // start time... l1.setStartTime(1234L); assertFalse(l1.equals(l2)); l2.setStartTime(1234L); assertTrue(l1.equals(l2)); } /** * Two objects that are equal are required to return the same hashCode. */ public void testHashCode() { SegmentedTimeline l1 = new SegmentedTimeline(1000, 5, 2); SegmentedTimeline l2 = new SegmentedTimeline(1000, 5, 2); assertTrue(l1.equals(l2)); int h1 = l1.hashCode(); int h2 = l2.hashCode(); assertEquals(h1, h2); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization2() { SegmentedTimeline l1 = new SegmentedTimeline(1000, 5, 2); SegmentedTimeline l2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(l1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); l2 = (SegmentedTimeline) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } boolean b = l1.equals(l2); assertTrue(b); } ////////////////////////////////////////////////////////////////////////// // utility methods ////////////////////////////////////////////////////////////////////////// /** * Tests a basic segmented timeline. */ public void testBasicSegmentedTimeline() { SegmentedTimeline stl = new SegmentedTimeline(10, 2, 3); stl.setStartTime(946684800000L); // 1-Jan-2000 assertFalse(stl.containsDomainValue(946684799999L)); assertTrue(stl.containsDomainValue(946684800000L)); assertTrue(stl.containsDomainValue(946684800019L)); assertFalse(stl.containsDomainValue(946684800020L)); assertFalse(stl.containsDomainValue(946684800049L)); assertTrue(stl.containsDomainValue(946684800050L)); assertTrue(stl.containsDomainValue(946684800069L)); assertFalse(stl.containsDomainValue(946684800070L)); assertFalse(stl.containsDomainValue(946684800099L)); assertTrue(stl.containsDomainValue(946684800100L)); assertEquals(0, stl.toTimelineValue(946684800000L)); assertEquals(19, stl.toTimelineValue(946684800019L)); assertEquals(20, stl.toTimelineValue(946684800020L)); assertEquals(20, stl.toTimelineValue(946684800049L)); assertEquals(20, stl.toTimelineValue(946684800050L)); assertEquals(39, stl.toTimelineValue(946684800069L)); assertEquals(40, stl.toTimelineValue(946684800070L)); assertEquals(40, stl.toTimelineValue(946684800099L)); assertEquals(40, stl.toTimelineValue(946684800100L)); assertEquals(946684800000L, stl.toMillisecond(0)); assertEquals(946684800019L, stl.toMillisecond(19)); assertEquals(946684800050L, stl.toMillisecond(20)); assertEquals(946684800069L, stl.toMillisecond(39)); assertEquals(946684800100L, stl.toMillisecond(40)); } /** * Tests a basic time line with one exception. */ public void testSegmentedTimelineWithException1() { SegmentedTimeline stl = new SegmentedTimeline(10, 2, 3); stl.setStartTime(946684800000L); // 1-Jan-2000 stl.addException(946684800050L); assertFalse(stl.containsDomainValue(946684799999L)); assertTrue(stl.containsDomainValue(946684800000L)); assertTrue(stl.containsDomainValue(946684800019L)); assertFalse(stl.containsDomainValue(946684800020L)); assertFalse(stl.containsDomainValue(946684800049L)); assertFalse(stl.containsDomainValue(946684800050L)); assertFalse(stl.containsDomainValue(946684800059L)); assertTrue(stl.containsDomainValue(946684800060L)); assertTrue(stl.containsDomainValue(946684800069L)); assertFalse(stl.containsDomainValue(946684800070L)); assertFalse(stl.containsDomainValue(946684800099L)); assertTrue(stl.containsDomainValue(946684800100L)); //long v = stl.toTimelineValue(946684800020L); assertEquals(0, stl.toTimelineValue(946684800000L)); assertEquals(19, stl.toTimelineValue(946684800019L)); assertEquals(20, stl.toTimelineValue(946684800020L)); assertEquals(20, stl.toTimelineValue(946684800049L)); assertEquals(20, stl.toTimelineValue(946684800050L)); assertEquals(29, stl.toTimelineValue(946684800069L)); assertEquals(30, stl.toTimelineValue(946684800070L)); assertEquals(30, stl.toTimelineValue(946684800099L)); assertEquals(30, stl.toTimelineValue(946684800100L)); assertEquals(946684800000L, stl.toMillisecond(0)); assertEquals(946684800019L, stl.toMillisecond(19)); assertEquals(946684800060L, stl.toMillisecond(20)); assertEquals(946684800069L, stl.toMillisecond(29)); assertEquals(946684800100L, stl.toMillisecond(30)); } ////////////////////////////////////////////////////////////////////////// // main method only for debug ////////////////////////////////////////////////////////////////////////// /** * Only use to debug JUnit suite. * * @param args ignored. * * @throws Exception if there is some problem. */ public static void main(String[] args) throws Exception { SegmentedTimelineTests test = new SegmentedTimelineTests("Test"); test.setUp(); test.testMondayThoughFridayExceptionSegments(); test.tearDown(); } }
[ { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "firstMondayAfter1900", "be_test_function_signature": "()J", "line_numbers": [ "354", "355", "359", "360", "361", "362", "363", "367" ], "method_line_rate": 0.875 }, { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "getSegmentSize", "be_test_function_signature": "()J", "line_numbers": [ "518" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "getSegmentsExcluded", "be_test_function_signature": "()I", "line_numbers": [ "461" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "getSegmentsIncluded", "be_test_function_signature": "()I", "line_numbers": [ "500" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "getStartTime", "be_test_function_signature": "()J", "line_numbers": [ "452" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "newFifteenMinuteTimeline", "be_test_function_signature": "()Lorg/jfree/chart/axis/SegmentedTimeline;", "line_numbers": [ "403", "405", "407", "408" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "newMondayThroughFridayTimeline", "be_test_function_signature": "()Lorg/jfree/chart/axis/SegmentedTimeline;", "line_numbers": [ "379", "381", "382" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "setBaseTimeline", "be_test_function_signature": "(Lorg/jfree/chart/axis/SegmentedTimeline;)V", "line_numbers": [ "557", "558", "559", "563", "564", "567", "568", "572", "574", "579", "580" ], "method_line_rate": 0.6363636363636364 }, { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "setStartTime", "be_test_function_signature": "(J)V", "line_numbers": [ "442", "443" ], "method_line_rate": 1 } ]
public class ToStringBuilderTest
@Test public void testReflectionArrayAndObjectCycle() throws Exception { final Object[] objects = new Object[1]; final SimpleReflectionTestFixture simple = new SimpleReflectionTestFixture(objects); objects[0] = simple; assertEquals( this.toBaseString(objects) + "[{" + this.toBaseString(simple) + "[o=" + this.toBaseString(objects) + "]" + "}]", ToStringBuilder.reflectionToString(objects)); assertEquals( this.toBaseString(simple) + "[o={" + this.toBaseString(simple) + "}]", ToStringBuilder.reflectionToString(simple)); }
// public ToStringBuilder appendSuper(final String superToString); // public ToStringBuilder appendToString(final String toString); // public Object getObject(); // public StringBuffer getStringBuffer(); // public ToStringStyle getStyle(); // @Override // public String toString(); // @Override // public String build(); // } // // // Abstract Java Test Class // package org.apache.commons.lang3.builder; // // import static org.junit.Assert.assertEquals; // import static org.junit.Assert.assertNull; // import static org.junit.Assert.assertSame; // import java.util.ArrayList; // import java.util.HashMap; // import java.util.List; // import java.util.Map; // import org.apache.commons.lang3.SystemUtils; // import org.junit.After; // import org.junit.Test; // // // // public class ToStringBuilderTest { // private final Integer base = Integer.valueOf(5); // private final String baseStr = base.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(base)); // // @After // public void after(); // @Test // public void testConstructorEx1(); // @Test // public void testConstructorEx2(); // @Test // public void testConstructorEx3(); // @Test // public void testGetSetDefault(); // @Test(expected=IllegalArgumentException.class) // public void testSetDefaultEx(); // @Test // public void testBlank(); // @Test // public void testReflectionInteger(); // @Test // public void testReflectionCharacter(); // @Test // public void testReflectionBoolean(); // private String toBaseString(final Object o); // public void assertReflectionArray(final String expected, final Object actual); // @Test // public void testReflectionObjectArray(); // @Test // public void testReflectionLongArray(); // @Test // public void testReflectionIntArray(); // @Test // public void testReflectionShortArray(); // @Test // public void testReflectionyteArray(); // @Test // public void testReflectionCharArray(); // @Test // public void testReflectionDoubleArray(); // @Test // public void testReflectionFloatArray(); // @Test // public void testReflectionBooleanArray(); // @Test // public void testReflectionFloatArrayArray(); // @Test // public void testReflectionLongArrayArray(); // @Test // public void testReflectionIntArrayArray(); // @Test // public void testReflectionhortArrayArray(); // @Test // public void testReflectionByteArrayArray(); // @Test // public void testReflectionCharArrayArray(); // @Test // public void testReflectionDoubleArrayArray(); // @Test // public void testReflectionBooleanArrayArray(); // @Test // public void testReflectionHierarchyArrayList(); // @Test // public void testReflectionHierarchy(); // @Test // public void testInnerClassReflection(); // @Test // public void testReflectionArrayCycle() throws Exception; // @Test // public void testReflectionArrayCycleLevel2() throws Exception; // @Test // public void testReflectionArrayArrayCycle() throws Exception; // @Test // public void testSimpleReflectionObjectCycle() throws Exception; // @Test // public void testSelfInstanceVarReflectionObjectCycle() throws Exception; // @Test // public void testSelfInstanceTwoVarsReflectionObjectCycle() throws Exception; // @Test // public void testReflectionObjectCycle() throws Exception; // @Test // public void testReflectionArrayAndObjectCycle() throws Exception; // void validateNullToStringStyleRegistry(); // @Test // public void testAppendSuper(); // @Test // public void testAppendToString(); // @Test // public void testObject(); // @Test // public void testObjectBuild(); // @Test // public void testLong(); // @SuppressWarnings("cast") // cast is not really needed, keep for consistency // @Test // public void testInt(); // @Test // public void testShort(); // @Test // public void testChar(); // @Test // public void testByte(); // @SuppressWarnings("cast") // @Test // public void testDouble(); // @Test // public void testFloat(); // @Test // public void testBoolean(); // @Test // public void testObjectArray(); // @Test // public void testLongArray(); // @Test // public void testIntArray(); // @Test // public void testShortArray(); // @Test // public void testByteArray(); // @Test // public void testCharArray(); // @Test // public void testDoubleArray(); // @Test // public void testFloatArray(); // @Test // public void testBooleanArray(); // @Test // public void testLongArrayArray(); // @Test // public void testIntArrayArray(); // @Test // public void testShortArrayArray(); // @Test // public void testByteArrayArray(); // @Test // public void testCharArrayArray(); // @Test // public void testDoubleArrayArray(); // @Test // public void testFloatArrayArray(); // @Test // public void testBooleanArrayArray(); // @Test // public void testObjectCycle(); // @Test // public void testSimpleReflectionStatics(); // @Test // public void testReflectionStatics(); // @Test // public void testInheritedReflectionStatics(); // public <T> String toStringWithStatics(final T object, final ToStringStyle style, final Class<? super T> reflectUpToClass); // @Test // public void test_setUpToClass_valid(); // @Test(expected=IllegalArgumentException.class) // public void test_setUpToClass_invalid(); // @Test // public void testReflectionNull(); // @Test // public void testAppendToStringUsingMultiLineStyle(); // @Override // public String toString(); // @Override // public String toString(); // @Override // public String toString(); // public SimpleReflectionTestFixture(); // public SimpleReflectionTestFixture(final Object o); // @Override // public String toString(); // public SelfInstanceVarReflectionTestFixture(); // @Override // public String toString(); // public SelfInstanceTwoVarsReflectionTestFixture(); // public String getOtherType(); // @Override // public String toString(); // @Override // public String toString(); // @Override // public String toString(); // @Override // public String toString(); // } // You are a professional Java test case writer, please create a test case named `testReflectionArrayAndObjectCycle` for the `ToStringBuilder` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test a nasty combination of arrays and Objects pointing to each other. * objects[0] -> SimpleReflectionTestFixture[ o -> objects ] * * @throws Exception */
src/test/java/org/apache/commons/lang3/builder/ToStringBuilderTest.java
package org.apache.commons.lang3.builder; import org.apache.commons.lang3.ObjectUtils;
public static ToStringStyle getDefaultStyle(); public static void setDefaultStyle(final ToStringStyle style); public static String reflectionToString(final Object object); public static String reflectionToString(final Object object, final ToStringStyle style); public static String reflectionToString(final Object object, final ToStringStyle style, final boolean outputTransients); public static <T> String reflectionToString( final T object, final ToStringStyle style, final boolean outputTransients, final Class<? super T> reflectUpToClass); public ToStringBuilder(final Object object); public ToStringBuilder(final Object object, final ToStringStyle style); public ToStringBuilder(final Object object, ToStringStyle style, StringBuffer buffer); public ToStringBuilder append(final boolean value); public ToStringBuilder append(final boolean[] array); public ToStringBuilder append(final byte value); public ToStringBuilder append(final byte[] array); public ToStringBuilder append(final char value); public ToStringBuilder append(final char[] array); public ToStringBuilder append(final double value); public ToStringBuilder append(final double[] array); public ToStringBuilder append(final float value); public ToStringBuilder append(final float[] array); public ToStringBuilder append(final int value); public ToStringBuilder append(final int[] array); public ToStringBuilder append(final long value); public ToStringBuilder append(final long[] array); public ToStringBuilder append(final Object obj); public ToStringBuilder append(final Object[] array); public ToStringBuilder append(final short value); public ToStringBuilder append(final short[] array); public ToStringBuilder append(final String fieldName, final boolean value); public ToStringBuilder append(final String fieldName, final boolean[] array); public ToStringBuilder append(final String fieldName, final boolean[] array, final boolean fullDetail); public ToStringBuilder append(final String fieldName, final byte value); public ToStringBuilder append(final String fieldName, final byte[] array); public ToStringBuilder append(final String fieldName, final byte[] array, final boolean fullDetail); public ToStringBuilder append(final String fieldName, final char value); public ToStringBuilder append(final String fieldName, final char[] array); public ToStringBuilder append(final String fieldName, final char[] array, final boolean fullDetail); public ToStringBuilder append(final String fieldName, final double value); public ToStringBuilder append(final String fieldName, final double[] array); public ToStringBuilder append(final String fieldName, final double[] array, final boolean fullDetail); public ToStringBuilder append(final String fieldName, final float value); public ToStringBuilder append(final String fieldName, final float[] array); public ToStringBuilder append(final String fieldName, final float[] array, final boolean fullDetail); public ToStringBuilder append(final String fieldName, final int value); public ToStringBuilder append(final String fieldName, final int[] array); public ToStringBuilder append(final String fieldName, final int[] array, final boolean fullDetail); public ToStringBuilder append(final String fieldName, final long value); public ToStringBuilder append(final String fieldName, final long[] array); public ToStringBuilder append(final String fieldName, final long[] array, final boolean fullDetail); public ToStringBuilder append(final String fieldName, final Object obj); public ToStringBuilder append(final String fieldName, final Object obj, final boolean fullDetail); public ToStringBuilder append(final String fieldName, final Object[] array); public ToStringBuilder append(final String fieldName, final Object[] array, final boolean fullDetail); public ToStringBuilder append(final String fieldName, final short value); public ToStringBuilder append(final String fieldName, final short[] array); public ToStringBuilder append(final String fieldName, final short[] array, final boolean fullDetail); public ToStringBuilder appendAsObjectToString(final Object object); public ToStringBuilder appendSuper(final String superToString); public ToStringBuilder appendToString(final String toString); public Object getObject(); public StringBuffer getStringBuffer(); public ToStringStyle getStyle(); @Override public String toString(); @Override public String build();
604
testReflectionArrayAndObjectCycle
```java public ToStringBuilder appendSuper(final String superToString); public ToStringBuilder appendToString(final String toString); public Object getObject(); public StringBuffer getStringBuffer(); public ToStringStyle getStyle(); @Override public String toString(); @Override public String build(); } // Abstract Java Test Class package org.apache.commons.lang3.builder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.SystemUtils; import org.junit.After; import org.junit.Test; public class ToStringBuilderTest { private final Integer base = Integer.valueOf(5); private final String baseStr = base.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(base)); @After public void after(); @Test public void testConstructorEx1(); @Test public void testConstructorEx2(); @Test public void testConstructorEx3(); @Test public void testGetSetDefault(); @Test(expected=IllegalArgumentException.class) public void testSetDefaultEx(); @Test public void testBlank(); @Test public void testReflectionInteger(); @Test public void testReflectionCharacter(); @Test public void testReflectionBoolean(); private String toBaseString(final Object o); public void assertReflectionArray(final String expected, final Object actual); @Test public void testReflectionObjectArray(); @Test public void testReflectionLongArray(); @Test public void testReflectionIntArray(); @Test public void testReflectionShortArray(); @Test public void testReflectionyteArray(); @Test public void testReflectionCharArray(); @Test public void testReflectionDoubleArray(); @Test public void testReflectionFloatArray(); @Test public void testReflectionBooleanArray(); @Test public void testReflectionFloatArrayArray(); @Test public void testReflectionLongArrayArray(); @Test public void testReflectionIntArrayArray(); @Test public void testReflectionhortArrayArray(); @Test public void testReflectionByteArrayArray(); @Test public void testReflectionCharArrayArray(); @Test public void testReflectionDoubleArrayArray(); @Test public void testReflectionBooleanArrayArray(); @Test public void testReflectionHierarchyArrayList(); @Test public void testReflectionHierarchy(); @Test public void testInnerClassReflection(); @Test public void testReflectionArrayCycle() throws Exception; @Test public void testReflectionArrayCycleLevel2() throws Exception; @Test public void testReflectionArrayArrayCycle() throws Exception; @Test public void testSimpleReflectionObjectCycle() throws Exception; @Test public void testSelfInstanceVarReflectionObjectCycle() throws Exception; @Test public void testSelfInstanceTwoVarsReflectionObjectCycle() throws Exception; @Test public void testReflectionObjectCycle() throws Exception; @Test public void testReflectionArrayAndObjectCycle() throws Exception; void validateNullToStringStyleRegistry(); @Test public void testAppendSuper(); @Test public void testAppendToString(); @Test public void testObject(); @Test public void testObjectBuild(); @Test public void testLong(); @SuppressWarnings("cast") // cast is not really needed, keep for consistency @Test public void testInt(); @Test public void testShort(); @Test public void testChar(); @Test public void testByte(); @SuppressWarnings("cast") @Test public void testDouble(); @Test public void testFloat(); @Test public void testBoolean(); @Test public void testObjectArray(); @Test public void testLongArray(); @Test public void testIntArray(); @Test public void testShortArray(); @Test public void testByteArray(); @Test public void testCharArray(); @Test public void testDoubleArray(); @Test public void testFloatArray(); @Test public void testBooleanArray(); @Test public void testLongArrayArray(); @Test public void testIntArrayArray(); @Test public void testShortArrayArray(); @Test public void testByteArrayArray(); @Test public void testCharArrayArray(); @Test public void testDoubleArrayArray(); @Test public void testFloatArrayArray(); @Test public void testBooleanArrayArray(); @Test public void testObjectCycle(); @Test public void testSimpleReflectionStatics(); @Test public void testReflectionStatics(); @Test public void testInheritedReflectionStatics(); public <T> String toStringWithStatics(final T object, final ToStringStyle style, final Class<? super T> reflectUpToClass); @Test public void test_setUpToClass_valid(); @Test(expected=IllegalArgumentException.class) public void test_setUpToClass_invalid(); @Test public void testReflectionNull(); @Test public void testAppendToStringUsingMultiLineStyle(); @Override public String toString(); @Override public String toString(); @Override public String toString(); public SimpleReflectionTestFixture(); public SimpleReflectionTestFixture(final Object o); @Override public String toString(); public SelfInstanceVarReflectionTestFixture(); @Override public String toString(); public SelfInstanceTwoVarsReflectionTestFixture(); public String getOtherType(); @Override public String toString(); @Override public String toString(); @Override public String toString(); @Override public String toString(); } ``` You are a professional Java test case writer, please create a test case named `testReflectionArrayAndObjectCycle` for the `ToStringBuilder` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test a nasty combination of arrays and Objects pointing to each other. * objects[0] -> SimpleReflectionTestFixture[ o -> objects ] * * @throws Exception */
584
// public ToStringBuilder appendSuper(final String superToString); // public ToStringBuilder appendToString(final String toString); // public Object getObject(); // public StringBuffer getStringBuffer(); // public ToStringStyle getStyle(); // @Override // public String toString(); // @Override // public String build(); // } // // // Abstract Java Test Class // package org.apache.commons.lang3.builder; // // import static org.junit.Assert.assertEquals; // import static org.junit.Assert.assertNull; // import static org.junit.Assert.assertSame; // import java.util.ArrayList; // import java.util.HashMap; // import java.util.List; // import java.util.Map; // import org.apache.commons.lang3.SystemUtils; // import org.junit.After; // import org.junit.Test; // // // // public class ToStringBuilderTest { // private final Integer base = Integer.valueOf(5); // private final String baseStr = base.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(base)); // // @After // public void after(); // @Test // public void testConstructorEx1(); // @Test // public void testConstructorEx2(); // @Test // public void testConstructorEx3(); // @Test // public void testGetSetDefault(); // @Test(expected=IllegalArgumentException.class) // public void testSetDefaultEx(); // @Test // public void testBlank(); // @Test // public void testReflectionInteger(); // @Test // public void testReflectionCharacter(); // @Test // public void testReflectionBoolean(); // private String toBaseString(final Object o); // public void assertReflectionArray(final String expected, final Object actual); // @Test // public void testReflectionObjectArray(); // @Test // public void testReflectionLongArray(); // @Test // public void testReflectionIntArray(); // @Test // public void testReflectionShortArray(); // @Test // public void testReflectionyteArray(); // @Test // public void testReflectionCharArray(); // @Test // public void testReflectionDoubleArray(); // @Test // public void testReflectionFloatArray(); // @Test // public void testReflectionBooleanArray(); // @Test // public void testReflectionFloatArrayArray(); // @Test // public void testReflectionLongArrayArray(); // @Test // public void testReflectionIntArrayArray(); // @Test // public void testReflectionhortArrayArray(); // @Test // public void testReflectionByteArrayArray(); // @Test // public void testReflectionCharArrayArray(); // @Test // public void testReflectionDoubleArrayArray(); // @Test // public void testReflectionBooleanArrayArray(); // @Test // public void testReflectionHierarchyArrayList(); // @Test // public void testReflectionHierarchy(); // @Test // public void testInnerClassReflection(); // @Test // public void testReflectionArrayCycle() throws Exception; // @Test // public void testReflectionArrayCycleLevel2() throws Exception; // @Test // public void testReflectionArrayArrayCycle() throws Exception; // @Test // public void testSimpleReflectionObjectCycle() throws Exception; // @Test // public void testSelfInstanceVarReflectionObjectCycle() throws Exception; // @Test // public void testSelfInstanceTwoVarsReflectionObjectCycle() throws Exception; // @Test // public void testReflectionObjectCycle() throws Exception; // @Test // public void testReflectionArrayAndObjectCycle() throws Exception; // void validateNullToStringStyleRegistry(); // @Test // public void testAppendSuper(); // @Test // public void testAppendToString(); // @Test // public void testObject(); // @Test // public void testObjectBuild(); // @Test // public void testLong(); // @SuppressWarnings("cast") // cast is not really needed, keep for consistency // @Test // public void testInt(); // @Test // public void testShort(); // @Test // public void testChar(); // @Test // public void testByte(); // @SuppressWarnings("cast") // @Test // public void testDouble(); // @Test // public void testFloat(); // @Test // public void testBoolean(); // @Test // public void testObjectArray(); // @Test // public void testLongArray(); // @Test // public void testIntArray(); // @Test // public void testShortArray(); // @Test // public void testByteArray(); // @Test // public void testCharArray(); // @Test // public void testDoubleArray(); // @Test // public void testFloatArray(); // @Test // public void testBooleanArray(); // @Test // public void testLongArrayArray(); // @Test // public void testIntArrayArray(); // @Test // public void testShortArrayArray(); // @Test // public void testByteArrayArray(); // @Test // public void testCharArrayArray(); // @Test // public void testDoubleArrayArray(); // @Test // public void testFloatArrayArray(); // @Test // public void testBooleanArrayArray(); // @Test // public void testObjectCycle(); // @Test // public void testSimpleReflectionStatics(); // @Test // public void testReflectionStatics(); // @Test // public void testInheritedReflectionStatics(); // public <T> String toStringWithStatics(final T object, final ToStringStyle style, final Class<? super T> reflectUpToClass); // @Test // public void test_setUpToClass_valid(); // @Test(expected=IllegalArgumentException.class) // public void test_setUpToClass_invalid(); // @Test // public void testReflectionNull(); // @Test // public void testAppendToStringUsingMultiLineStyle(); // @Override // public String toString(); // @Override // public String toString(); // @Override // public String toString(); // public SimpleReflectionTestFixture(); // public SimpleReflectionTestFixture(final Object o); // @Override // public String toString(); // public SelfInstanceVarReflectionTestFixture(); // @Override // public String toString(); // public SelfInstanceTwoVarsReflectionTestFixture(); // public String getOtherType(); // @Override // public String toString(); // @Override // public String toString(); // @Override // public String toString(); // @Override // public String toString(); // } // You are a professional Java test case writer, please create a test case named `testReflectionArrayAndObjectCycle` for the `ToStringBuilder` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test a nasty combination of arrays and Objects pointing to each other. * objects[0] -> SimpleReflectionTestFixture[ o -> objects ] * * @throws Exception */ @Test public void testReflectionArrayAndObjectCycle() throws Exception {
/** * Test a nasty combination of arrays and Objects pointing to each other. * objects[0] -> SimpleReflectionTestFixture[ o -> objects ] * * @throws Exception */
1
org.apache.commons.lang3.builder.ToStringBuilder
src/test/java
```java public ToStringBuilder appendSuper(final String superToString); public ToStringBuilder appendToString(final String toString); public Object getObject(); public StringBuffer getStringBuffer(); public ToStringStyle getStyle(); @Override public String toString(); @Override public String build(); } // Abstract Java Test Class package org.apache.commons.lang3.builder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.SystemUtils; import org.junit.After; import org.junit.Test; public class ToStringBuilderTest { private final Integer base = Integer.valueOf(5); private final String baseStr = base.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(base)); @After public void after(); @Test public void testConstructorEx1(); @Test public void testConstructorEx2(); @Test public void testConstructorEx3(); @Test public void testGetSetDefault(); @Test(expected=IllegalArgumentException.class) public void testSetDefaultEx(); @Test public void testBlank(); @Test public void testReflectionInteger(); @Test public void testReflectionCharacter(); @Test public void testReflectionBoolean(); private String toBaseString(final Object o); public void assertReflectionArray(final String expected, final Object actual); @Test public void testReflectionObjectArray(); @Test public void testReflectionLongArray(); @Test public void testReflectionIntArray(); @Test public void testReflectionShortArray(); @Test public void testReflectionyteArray(); @Test public void testReflectionCharArray(); @Test public void testReflectionDoubleArray(); @Test public void testReflectionFloatArray(); @Test public void testReflectionBooleanArray(); @Test public void testReflectionFloatArrayArray(); @Test public void testReflectionLongArrayArray(); @Test public void testReflectionIntArrayArray(); @Test public void testReflectionhortArrayArray(); @Test public void testReflectionByteArrayArray(); @Test public void testReflectionCharArrayArray(); @Test public void testReflectionDoubleArrayArray(); @Test public void testReflectionBooleanArrayArray(); @Test public void testReflectionHierarchyArrayList(); @Test public void testReflectionHierarchy(); @Test public void testInnerClassReflection(); @Test public void testReflectionArrayCycle() throws Exception; @Test public void testReflectionArrayCycleLevel2() throws Exception; @Test public void testReflectionArrayArrayCycle() throws Exception; @Test public void testSimpleReflectionObjectCycle() throws Exception; @Test public void testSelfInstanceVarReflectionObjectCycle() throws Exception; @Test public void testSelfInstanceTwoVarsReflectionObjectCycle() throws Exception; @Test public void testReflectionObjectCycle() throws Exception; @Test public void testReflectionArrayAndObjectCycle() throws Exception; void validateNullToStringStyleRegistry(); @Test public void testAppendSuper(); @Test public void testAppendToString(); @Test public void testObject(); @Test public void testObjectBuild(); @Test public void testLong(); @SuppressWarnings("cast") // cast is not really needed, keep for consistency @Test public void testInt(); @Test public void testShort(); @Test public void testChar(); @Test public void testByte(); @SuppressWarnings("cast") @Test public void testDouble(); @Test public void testFloat(); @Test public void testBoolean(); @Test public void testObjectArray(); @Test public void testLongArray(); @Test public void testIntArray(); @Test public void testShortArray(); @Test public void testByteArray(); @Test public void testCharArray(); @Test public void testDoubleArray(); @Test public void testFloatArray(); @Test public void testBooleanArray(); @Test public void testLongArrayArray(); @Test public void testIntArrayArray(); @Test public void testShortArrayArray(); @Test public void testByteArrayArray(); @Test public void testCharArrayArray(); @Test public void testDoubleArrayArray(); @Test public void testFloatArrayArray(); @Test public void testBooleanArrayArray(); @Test public void testObjectCycle(); @Test public void testSimpleReflectionStatics(); @Test public void testReflectionStatics(); @Test public void testInheritedReflectionStatics(); public <T> String toStringWithStatics(final T object, final ToStringStyle style, final Class<? super T> reflectUpToClass); @Test public void test_setUpToClass_valid(); @Test(expected=IllegalArgumentException.class) public void test_setUpToClass_invalid(); @Test public void testReflectionNull(); @Test public void testAppendToStringUsingMultiLineStyle(); @Override public String toString(); @Override public String toString(); @Override public String toString(); public SimpleReflectionTestFixture(); public SimpleReflectionTestFixture(final Object o); @Override public String toString(); public SelfInstanceVarReflectionTestFixture(); @Override public String toString(); public SelfInstanceTwoVarsReflectionTestFixture(); public String getOtherType(); @Override public String toString(); @Override public String toString(); @Override public String toString(); @Override public String toString(); } ``` You are a professional Java test case writer, please create a test case named `testReflectionArrayAndObjectCycle` for the `ToStringBuilder` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test a nasty combination of arrays and Objects pointing to each other. * objects[0] -> SimpleReflectionTestFixture[ o -> objects ] * * @throws Exception */ @Test public void testReflectionArrayAndObjectCycle() throws Exception { ```
public class ToStringBuilder implements Builder<String>
package org.apache.commons.lang3.builder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.SystemUtils; import org.junit.After; import org.junit.Test;
@After public void after(); @Test public void testConstructorEx1(); @Test public void testConstructorEx2(); @Test public void testConstructorEx3(); @Test public void testGetSetDefault(); @Test(expected=IllegalArgumentException.class) public void testSetDefaultEx(); @Test public void testBlank(); @Test public void testReflectionInteger(); @Test public void testReflectionCharacter(); @Test public void testReflectionBoolean(); private String toBaseString(final Object o); public void assertReflectionArray(final String expected, final Object actual); @Test public void testReflectionObjectArray(); @Test public void testReflectionLongArray(); @Test public void testReflectionIntArray(); @Test public void testReflectionShortArray(); @Test public void testReflectionyteArray(); @Test public void testReflectionCharArray(); @Test public void testReflectionDoubleArray(); @Test public void testReflectionFloatArray(); @Test public void testReflectionBooleanArray(); @Test public void testReflectionFloatArrayArray(); @Test public void testReflectionLongArrayArray(); @Test public void testReflectionIntArrayArray(); @Test public void testReflectionhortArrayArray(); @Test public void testReflectionByteArrayArray(); @Test public void testReflectionCharArrayArray(); @Test public void testReflectionDoubleArrayArray(); @Test public void testReflectionBooleanArrayArray(); @Test public void testReflectionHierarchyArrayList(); @Test public void testReflectionHierarchy(); @Test public void testInnerClassReflection(); @Test public void testReflectionArrayCycle() throws Exception; @Test public void testReflectionArrayCycleLevel2() throws Exception; @Test public void testReflectionArrayArrayCycle() throws Exception; @Test public void testSimpleReflectionObjectCycle() throws Exception; @Test public void testSelfInstanceVarReflectionObjectCycle() throws Exception; @Test public void testSelfInstanceTwoVarsReflectionObjectCycle() throws Exception; @Test public void testReflectionObjectCycle() throws Exception; @Test public void testReflectionArrayAndObjectCycle() throws Exception; void validateNullToStringStyleRegistry(); @Test public void testAppendSuper(); @Test public void testAppendToString(); @Test public void testObject(); @Test public void testObjectBuild(); @Test public void testLong(); @SuppressWarnings("cast") // cast is not really needed, keep for consistency @Test public void testInt(); @Test public void testShort(); @Test public void testChar(); @Test public void testByte(); @SuppressWarnings("cast") @Test public void testDouble(); @Test public void testFloat(); @Test public void testBoolean(); @Test public void testObjectArray(); @Test public void testLongArray(); @Test public void testIntArray(); @Test public void testShortArray(); @Test public void testByteArray(); @Test public void testCharArray(); @Test public void testDoubleArray(); @Test public void testFloatArray(); @Test public void testBooleanArray(); @Test public void testLongArrayArray(); @Test public void testIntArrayArray(); @Test public void testShortArrayArray(); @Test public void testByteArrayArray(); @Test public void testCharArrayArray(); @Test public void testDoubleArrayArray(); @Test public void testFloatArrayArray(); @Test public void testBooleanArrayArray(); @Test public void testObjectCycle(); @Test public void testSimpleReflectionStatics(); @Test public void testReflectionStatics(); @Test public void testInheritedReflectionStatics(); public <T> String toStringWithStatics(final T object, final ToStringStyle style, final Class<? super T> reflectUpToClass); @Test public void test_setUpToClass_valid(); @Test(expected=IllegalArgumentException.class) public void test_setUpToClass_invalid(); @Test public void testReflectionNull(); @Test public void testAppendToStringUsingMultiLineStyle(); @Override public String toString(); @Override public String toString(); @Override public String toString(); public SimpleReflectionTestFixture(); public SimpleReflectionTestFixture(final Object o); @Override public String toString(); public SelfInstanceVarReflectionTestFixture(); @Override public String toString(); public SelfInstanceTwoVarsReflectionTestFixture(); public String getOtherType(); @Override public String toString(); @Override public String toString(); @Override public String toString(); @Override public String toString();
1487d3b5aad2c5f87b433a24464ffcd2e1a84b7382296593cd691a5ae77c3a41
[ "org.apache.commons.lang3.builder.ToStringBuilderTest::testReflectionArrayAndObjectCycle" ]
private static volatile ToStringStyle defaultStyle = ToStringStyle.DEFAULT_STYLE; private final StringBuffer buffer; private final Object object; private final ToStringStyle style;
@Test public void testReflectionArrayAndObjectCycle() throws Exception
private final Integer base = Integer.valueOf(5); private final String baseStr = base.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(base));
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.builder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.SystemUtils; import org.junit.After; import org.junit.Test; /** * Unit tests for {@link org.apache.commons.lang3.builder.ToStringBuilder}. * * @version $Id$ */ public class ToStringBuilderTest { private final Integer base = Integer.valueOf(5); private final String baseStr = base.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(base)); /* * All tests should leave the registry empty. */ @After public void after(){ validateNullToStringStyleRegistry(); } //----------------------------------------------------------------------- @Test public void testConstructorEx1() { assertEquals("<null>", new ToStringBuilder(null).toString()); } @Test public void testConstructorEx2() { assertEquals("<null>", new ToStringBuilder(null, null).toString()); new ToStringBuilder(this.base, null).toString(); } @Test public void testConstructorEx3() { assertEquals("<null>", new ToStringBuilder(null, null, null).toString()); new ToStringBuilder(this.base, null, null).toString(); new ToStringBuilder(this.base, ToStringStyle.DEFAULT_STYLE, null).toString(); } @Test public void testGetSetDefault() { try { ToStringBuilder.setDefaultStyle(ToStringStyle.NO_FIELD_NAMES_STYLE); assertSame(ToStringStyle.NO_FIELD_NAMES_STYLE, ToStringBuilder.getDefaultStyle()); } finally { // reset for other tests ToStringBuilder.setDefaultStyle(ToStringStyle.DEFAULT_STYLE); } } @Test(expected=IllegalArgumentException.class) public void testSetDefaultEx() { ToStringBuilder.setDefaultStyle(null); } @Test public void testBlank() { assertEquals(baseStr + "[]", new ToStringBuilder(base).toString()); } /** * Test wrapper for int primitive. */ @Test public void testReflectionInteger() { assertEquals(baseStr + "[value=5]", ToStringBuilder.reflectionToString(base)); } /** * Test wrapper for char primitive. */ @Test public void testReflectionCharacter() { final Character c = new Character('A'); assertEquals(this.toBaseString(c) + "[value=A]", ToStringBuilder.reflectionToString(c)); } /** * Test wrapper for char boolean. */ @Test public void testReflectionBoolean() { Boolean b; b = Boolean.TRUE; assertEquals(this.toBaseString(b) + "[value=true]", ToStringBuilder.reflectionToString(b)); b = Boolean.FALSE; assertEquals(this.toBaseString(b) + "[value=false]", ToStringBuilder.reflectionToString(b)); } /** * Create the same toString() as Object.toString(). * @param o the object to create the string for. * @return a String in the Object.toString format. */ private String toBaseString(final Object o) { return o.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(o)); } // Reflection Array tests // // Note on the following line of code repeated in the reflection array tests. // // assertReflectionArray("<null>", array); // // The expected value is not baseStr + "[<null>]" since array==null and is typed as Object. // The null array does not carry array type information. // If we added a primitive array type constructor and pile of associated methods, // then type declaring type information could be carried forward. IMHO, null is null. // // Gary Gregory - 2003-03-12 - ggregory@seagullsw.com // public void assertReflectionArray(final String expected, final Object actual) { if (actual == null) { // Until ToStringBuilder supports null objects. return; } assertEquals(expected, ToStringBuilder.reflectionToString(actual)); assertEquals(expected, ToStringBuilder.reflectionToString(actual, null)); assertEquals(expected, ToStringBuilder.reflectionToString(actual, null, true)); assertEquals(expected, ToStringBuilder.reflectionToString(actual, null, false)); } @Test public void testReflectionObjectArray() { Object[] array = new Object[] { null, base, new int[] { 3, 6 } }; final String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{<null>,5,{3,6}}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("<null>", array); } @Test public void testReflectionLongArray() { long[] array = new long[] { 1, 2, -3, 4 }; final String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("<null>", array); } @Test public void testReflectionIntArray() { int[] array = new int[] { 1, 2, -3, 4 }; final String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("<null>", array); } @Test public void testReflectionShortArray() { short[] array = new short[] { 1, 2, -3, 4 }; final String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("<null>", array); } @Test public void testReflectionyteArray() { byte[] array = new byte[] { 1, 2, -3, 4 }; final String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{1,2,-3,4}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("<null>", array); } @Test public void testReflectionCharArray() { char[] array = new char[] { 'A', '2', '_', 'D' }; final String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{A,2,_,D}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("<null>", array); } @Test public void testReflectionDoubleArray() { double[] array = new double[] { 1.0, 2.9876, -3.00001, 4.3 }; final String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("<null>", array); } @Test public void testReflectionFloatArray() { float[] array = new float[] { 1.0f, 2.9876f, -3.00001f, 4.3f }; final String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("<null>", array); } @Test public void testReflectionBooleanArray() { boolean[] array = new boolean[] { true, false, false }; final String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{true,false,false}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("<null>", array); } // Reflection Array Array tests @Test public void testReflectionFloatArrayArray() { float[][] array = new float[][] { { 1.0f, 2.29686f }, null, { Float.NaN } }; final String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("<null>", array); } @Test public void testReflectionLongArrayArray() { long[][] array = new long[][] { { 1, 2 }, null, { 5 } }; final String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("<null>", array); } @Test public void testReflectionIntArrayArray() { int[][] array = new int[][] { { 1, 2 }, null, { 5 } }; final String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("<null>", array); } @Test public void testReflectionhortArrayArray() { short[][] array = new short[][] { { 1, 2 }, null, { 5 } }; final String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("<null>", array); } @Test public void testReflectionByteArrayArray() { byte[][] array = new byte[][] { { 1, 2 }, null, { 5 } }; final String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{{1,2},<null>,{5}}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("<null>", array); } @Test public void testReflectionCharArrayArray() { char[][] array = new char[][] { { 'A', 'B' }, null, { 'p' } }; final String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{{A,B},<null>,{p}}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("<null>", array); } @Test public void testReflectionDoubleArrayArray() { double[][] array = new double[][] { { 1.0, 2.29686 }, null, { Double.NaN } }; final String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("<null>", array); } @Test public void testReflectionBooleanArrayArray() { boolean[][] array = new boolean[][] { { true, false }, null, { false } }; final String baseStr = this.toBaseString(array); assertEquals(baseStr + "[{{true,false},<null>,{false}}]", ToStringBuilder.reflectionToString(array)); assertEquals(baseStr + "[{{true,false},<null>,{false}}]", ToStringBuilder.reflectionToString(array)); array = null; assertReflectionArray("<null>", array); } // Reflection hierarchy tests @Test public void testReflectionHierarchyArrayList() {} // Defects4J: flaky method // @Test // public void testReflectionHierarchyArrayList() { // final List<Object> base = new ArrayList<Object>(); // final String baseStr = this.toBaseString(base); // // note, the test data depends on the internal representation of the ArrayList, which may differ between JDK versions and vendors // final String expectedWithTransients = baseStr + "[elementData={<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>},size=0,modCount=0]"; // final String toStringWithTransients = ToStringBuilder.reflectionToString(base, null, true); // if (!expectedWithTransients.equals(toStringWithTransients)) { // // representation different for IBM JDK 1.6.0, LANG-727 // if (!("IBM Corporation".equals(SystemUtils.JAVA_VENDOR) && "1.6".equals(SystemUtils.JAVA_SPECIFICATION_VERSION))) { // assertEquals(expectedWithTransients, toStringWithTransients); // } // } // final String expectedWithoutTransients = baseStr + "[size=0]"; // final String toStringWithoutTransients = ToStringBuilder.reflectionToString(base, null, false); // if (!expectedWithoutTransients.equals(toStringWithoutTransients)) { // // representation different for IBM JDK 1.6.0, LANG-727 // if (!("IBM Corporation".equals(SystemUtils.JAVA_VENDOR) && "1.6".equals(SystemUtils.JAVA_SPECIFICATION_VERSION))) { // assertEquals(expectedWithoutTransients, toStringWithoutTransients); // } // } // } @Test public void testReflectionHierarchy() { final ReflectionTestFixtureA baseA = new ReflectionTestFixtureA(); String baseStr = this.toBaseString(baseA); assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA)); assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null)); assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false)); assertEquals(baseStr + "[a=a,transientA=t]", ToStringBuilder.reflectionToString(baseA, null, true)); assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false, null)); assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false, Object.class)); assertEquals(baseStr + "[a=a]", ToStringBuilder.reflectionToString(baseA, null, false, ReflectionTestFixtureA.class)); final ReflectionTestFixtureB baseB = new ReflectionTestFixtureB(); baseStr = this.toBaseString(baseB); assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB)); assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB)); assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null)); assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false)); assertEquals(baseStr + "[b=b,transientB=t,a=a,transientA=t]", ToStringBuilder.reflectionToString(baseB, null, true)); assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false, null)); assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false, Object.class)); assertEquals(baseStr + "[b=b,a=a]", ToStringBuilder.reflectionToString(baseB, null, false, ReflectionTestFixtureA.class)); assertEquals(baseStr + "[b=b]", ToStringBuilder.reflectionToString(baseB, null, false, ReflectionTestFixtureB.class)); } static class ReflectionTestFixtureA { @SuppressWarnings("unused") private final char a='a'; @SuppressWarnings("unused") private transient char transientA='t'; } static class ReflectionTestFixtureB extends ReflectionTestFixtureA { @SuppressWarnings("unused") private final char b='b'; @SuppressWarnings("unused") private transient char transientB='t'; } @Test public void testInnerClassReflection() { final Outer outer = new Outer(); assertEquals(toBaseString(outer) + "[inner=" + toBaseString(outer.inner) + "[]]", outer.toString()); } static class Outer { Inner inner = new Inner(); class Inner { @Override public String toString() { return ToStringBuilder.reflectionToString(this); } } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } } // Reflection cycle tests /** * Test an array element pointing to its container. */ @Test public void testReflectionArrayCycle() throws Exception { final Object[] objects = new Object[1]; objects[0] = objects; assertEquals( this.toBaseString(objects) + "[{" + this.toBaseString(objects) + "}]", ToStringBuilder.reflectionToString(objects)); } /** * Test an array element pointing to its container. */ @Test public void testReflectionArrayCycleLevel2() throws Exception { final Object[] objects = new Object[1]; final Object[] objectsLevel2 = new Object[1]; objects[0] = objectsLevel2; objectsLevel2[0] = objects; assertEquals( this.toBaseString(objects) + "[{{" + this.toBaseString(objects) + "}}]", ToStringBuilder.reflectionToString(objects)); assertEquals( this.toBaseString(objectsLevel2) + "[{{" + this.toBaseString(objectsLevel2) + "}}]", ToStringBuilder.reflectionToString(objectsLevel2)); } @Test public void testReflectionArrayArrayCycle() throws Exception { final Object[][] objects = new Object[2][2]; objects[0][0] = objects; objects[0][1] = objects; objects[1][0] = objects; objects[1][1] = objects; final String basicToString = this.toBaseString(objects); assertEquals( basicToString + "[{{" + basicToString + "," + basicToString + "},{" + basicToString + "," + basicToString + "}}]", ToStringBuilder.reflectionToString(objects)); } /** * A reflection test fixture. */ static class ReflectionTestCycleA { ReflectionTestCycleB b; @Override public String toString() { return ToStringBuilder.reflectionToString(this); } } /** * A reflection test fixture. */ static class ReflectionTestCycleB { ReflectionTestCycleA a; @Override public String toString() { return ToStringBuilder.reflectionToString(this); } } /** * A reflection test fixture. */ static class SimpleReflectionTestFixture { Object o; public SimpleReflectionTestFixture() { } public SimpleReflectionTestFixture(final Object o) { this.o = o; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } } private static class SelfInstanceVarReflectionTestFixture { @SuppressWarnings("unused") private final SelfInstanceVarReflectionTestFixture typeIsSelf; public SelfInstanceVarReflectionTestFixture() { this.typeIsSelf = this; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } } private static class SelfInstanceTwoVarsReflectionTestFixture { @SuppressWarnings("unused") private final SelfInstanceTwoVarsReflectionTestFixture typeIsSelf; private final String otherType = "The Other Type"; public SelfInstanceTwoVarsReflectionTestFixture() { this.typeIsSelf = this; } public String getOtherType(){ return this.otherType; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } } /** * Test an Object pointing to itself, the simplest test. * * @throws Exception */ @Test public void testSimpleReflectionObjectCycle() throws Exception { final SimpleReflectionTestFixture simple = new SimpleReflectionTestFixture(); simple.o = simple; assertEquals(this.toBaseString(simple) + "[o=" + this.toBaseString(simple) + "]", simple.toString()); } /** * Test a class that defines an ivar pointing to itself. * * @throws Exception */ @Test public void testSelfInstanceVarReflectionObjectCycle() throws Exception { final SelfInstanceVarReflectionTestFixture test = new SelfInstanceVarReflectionTestFixture(); assertEquals(this.toBaseString(test) + "[typeIsSelf=" + this.toBaseString(test) + "]", test.toString()); } /** * Test a class that defines an ivar pointing to itself. This test was * created to show that handling cyclical object resulted in a missing endFieldSeparator call. * * @throws Exception */ @Test public void testSelfInstanceTwoVarsReflectionObjectCycle() throws Exception { final SelfInstanceTwoVarsReflectionTestFixture test = new SelfInstanceTwoVarsReflectionTestFixture(); assertEquals(this.toBaseString(test) + "[typeIsSelf=" + this.toBaseString(test) + ",otherType=" + test.getOtherType().toString() + "]", test.toString()); } /** * Test Objects pointing to each other. * * @throws Exception */ @Test public void testReflectionObjectCycle() throws Exception { final ReflectionTestCycleA a = new ReflectionTestCycleA(); final ReflectionTestCycleB b = new ReflectionTestCycleB(); a.b = b; b.a = a; assertEquals( this.toBaseString(a) + "[b=" + this.toBaseString(b) + "[a=" + this.toBaseString(a) + "]]", a.toString()); } /** * Test a nasty combination of arrays and Objects pointing to each other. * objects[0] -> SimpleReflectionTestFixture[ o -> objects ] * * @throws Exception */ @Test public void testReflectionArrayAndObjectCycle() throws Exception { final Object[] objects = new Object[1]; final SimpleReflectionTestFixture simple = new SimpleReflectionTestFixture(objects); objects[0] = simple; assertEquals( this.toBaseString(objects) + "[{" + this.toBaseString(simple) + "[o=" + this.toBaseString(objects) + "]" + "}]", ToStringBuilder.reflectionToString(objects)); assertEquals( this.toBaseString(simple) + "[o={" + this.toBaseString(simple) + "}]", ToStringBuilder.reflectionToString(simple)); } void validateNullToStringStyleRegistry() { final Map<Object, Object> registry = ToStringStyle.getRegistry(); assertNull("Expected null, actual: "+registry, registry); } // End: Reflection cycle tests @Test public void testAppendSuper() { assertEquals(baseStr + "[]", new ToStringBuilder(base).appendSuper("Integer@8888[]").toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).appendSuper("Integer@8888[<null>]").toString()); assertEquals(baseStr + "[a=hello]", new ToStringBuilder(base).appendSuper("Integer@8888[]").append("a", "hello").toString()); assertEquals(baseStr + "[<null>,a=hello]", new ToStringBuilder(base).appendSuper("Integer@8888[<null>]").append("a", "hello").toString()); assertEquals(baseStr + "[a=hello]", new ToStringBuilder(base).appendSuper(null).append("a", "hello").toString()); } @Test public void testAppendToString() { assertEquals(baseStr + "[]", new ToStringBuilder(base).appendToString("Integer@8888[]").toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).appendToString("Integer@8888[<null>]").toString()); assertEquals(baseStr + "[a=hello]", new ToStringBuilder(base).appendToString("Integer@8888[]").append("a", "hello").toString()); assertEquals(baseStr + "[<null>,a=hello]", new ToStringBuilder(base).appendToString("Integer@8888[<null>]").append("a", "hello").toString()); assertEquals(baseStr + "[a=hello]", new ToStringBuilder(base).appendToString(null).append("a", "hello").toString()); } @Test public void testObject() { final Integer i3 = Integer.valueOf(3); final Integer i4 = Integer.valueOf(4); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) null).toString()); assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(i3).toString()); assertEquals(baseStr + "[a=<null>]", new ToStringBuilder(base).append("a", (Object) null).toString()); assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", i3).toString()); assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString()); assertEquals(baseStr + "[a=<Integer>]", new ToStringBuilder(base).append("a", i3, false).toString()); assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", new ArrayList<Object>(), false).toString()); assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", new ArrayList<Object>(), true).toString()); assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", new HashMap<Object, Object>(), false).toString()); assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", new HashMap<Object, Object>(), true).toString()); assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString()); assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString()); } @Test public void testObjectBuild() { final Integer i3 = Integer.valueOf(3); final Integer i4 = Integer.valueOf(4); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) null).build()); assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(i3).build()); assertEquals(baseStr + "[a=<null>]", new ToStringBuilder(base).append("a", (Object) null).build()); assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", i3).build()); assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", i3).append("b", i4).build()); assertEquals(baseStr + "[a=<Integer>]", new ToStringBuilder(base).append("a", i3, false).build()); assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", new ArrayList<Object>(), false).build()); assertEquals(baseStr + "[a=[]]", new ToStringBuilder(base).append("a", new ArrayList<Object>(), true).build()); assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", new HashMap<Object, Object>(), false).build()); assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", new HashMap<Object, Object>(), true).build()); assertEquals(baseStr + "[a=<size=0>]", new ToStringBuilder(base).append("a", (Object) new String[0], false).build()); assertEquals(baseStr + "[a={}]", new ToStringBuilder(base).append("a", (Object) new String[0], true).build()); } @Test public void testLong() { assertEquals(baseStr + "[3]", new ToStringBuilder(base).append(3L).toString()); assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", 3L).toString()); assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", 3L).append("b", 4L).toString()); } @SuppressWarnings("cast") // cast is not really needed, keep for consistency @Test public void testInt() { assertEquals(baseStr + "[3]", new ToStringBuilder(base).append((int) 3).toString()); assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", (int) 3).toString()); assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", (int) 3).append("b", (int) 4).toString()); } @Test public void testShort() { assertEquals(baseStr + "[3]", new ToStringBuilder(base).append((short) 3).toString()); assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", (short) 3).toString()); assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", (short) 3).append("b", (short) 4).toString()); } @Test public void testChar() { assertEquals(baseStr + "[A]", new ToStringBuilder(base).append((char) 65).toString()); assertEquals(baseStr + "[a=A]", new ToStringBuilder(base).append("a", (char) 65).toString()); assertEquals(baseStr + "[a=A,b=B]", new ToStringBuilder(base).append("a", (char) 65).append("b", (char) 66).toString()); } @Test public void testByte() { assertEquals(baseStr + "[3]", new ToStringBuilder(base).append((byte) 3).toString()); assertEquals(baseStr + "[a=3]", new ToStringBuilder(base).append("a", (byte) 3).toString()); assertEquals(baseStr + "[a=3,b=4]", new ToStringBuilder(base).append("a", (byte) 3).append("b", (byte) 4).toString()); } @SuppressWarnings("cast") @Test public void testDouble() { assertEquals(baseStr + "[3.2]", new ToStringBuilder(base).append((double) 3.2).toString()); assertEquals(baseStr + "[a=3.2]", new ToStringBuilder(base).append("a", (double) 3.2).toString()); assertEquals(baseStr + "[a=3.2,b=4.3]", new ToStringBuilder(base).append("a", (double) 3.2).append("b", (double) 4.3).toString()); } @Test public void testFloat() { assertEquals(baseStr + "[3.2]", new ToStringBuilder(base).append((float) 3.2).toString()); assertEquals(baseStr + "[a=3.2]", new ToStringBuilder(base).append("a", (float) 3.2).toString()); assertEquals(baseStr + "[a=3.2,b=4.3]", new ToStringBuilder(base).append("a", (float) 3.2).append("b", (float) 4.3).toString()); } @Test public void testBoolean() { assertEquals(baseStr + "[true]", new ToStringBuilder(base).append(true).toString()); assertEquals(baseStr + "[a=true]", new ToStringBuilder(base).append("a", true).toString()); assertEquals(baseStr + "[a=true,b=false]", new ToStringBuilder(base).append("a", true).append("b", false).toString()); } @Test public void testObjectArray() { Object[] array = new Object[] {null, base, new int[] {3, 6}}; assertEquals(baseStr + "[{<null>,5,{3,6}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{<null>,5,{3,6}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString()); } @Test public void testLongArray() { long[] array = new long[] {1, 2, -3, 4}; assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString()); } @Test public void testIntArray() { int[] array = new int[] {1, 2, -3, 4}; assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString()); } @Test public void testShortArray() { short[] array = new short[] {1, 2, -3, 4}; assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString()); } @Test public void testByteArray() { byte[] array = new byte[] {1, 2, -3, 4}; assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString()); } @Test public void testCharArray() { char[] array = new char[] {'A', '2', '_', 'D'}; assertEquals(baseStr + "[{A,2,_,D}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{A,2,_,D}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString()); } @Test public void testDoubleArray() { double[] array = new double[] {1.0, 2.9876, -3.00001, 4.3}; assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString()); } @Test public void testFloatArray() { float[] array = new float[] {1.0f, 2.9876f, -3.00001f, 4.3f}; assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString()); } @Test public void testBooleanArray() { boolean[] array = new boolean[] {true, false, false}; assertEquals(baseStr + "[{true,false,false}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{true,false,false}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString()); } @Test public void testLongArrayArray() { long[][] array = new long[][] {{1, 2}, null, {5}}; assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString()); } @Test public void testIntArrayArray() { int[][] array = new int[][] {{1, 2}, null, {5}}; assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString()); } @Test public void testShortArrayArray() { short[][] array = new short[][] {{1, 2}, null, {5}}; assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString()); } @Test public void testByteArrayArray() { byte[][] array = new byte[][] {{1, 2}, null, {5}}; assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString()); } @Test public void testCharArrayArray() { char[][] array = new char[][] {{'A', 'B'}, null, {'p'}}; assertEquals(baseStr + "[{{A,B},<null>,{p}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{A,B},<null>,{p}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString()); } @Test public void testDoubleArrayArray() { double[][] array = new double[][] {{1.0, 2.29686}, null, {Double.NaN}}; assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString()); } @Test public void testFloatArrayArray() { float[][] array = new float[][] {{1.0f, 2.29686f}, null, {Float.NaN}}; assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString()); } @Test public void testBooleanArrayArray() { boolean[][] array = new boolean[][] {{true, false}, null, {false}}; assertEquals(baseStr + "[{{true,false},<null>,{false}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{true,false},<null>,{false}}]", new ToStringBuilder(base).append((Object) array).toString()); array = null; assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append((Object) array).toString()); } @Test public void testObjectCycle() { final ObjectCycle a = new ObjectCycle(); final ObjectCycle b = new ObjectCycle(); a.obj = b; b.obj = a; final String expected = toBaseString(a) + "[" + toBaseString(b) + "[" + toBaseString(a) + "]]"; assertEquals(expected, a.toString()); } static class ObjectCycle { Object obj; @Override public String toString() { return new ToStringBuilder(this).append(obj).toString(); } } @Test public void testSimpleReflectionStatics() { final SimpleReflectionStaticFieldsFixture instance1 = new SimpleReflectionStaticFieldsFixture(); assertEquals( this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345]", ReflectionToStringBuilder.toString(instance1, null, false, true, SimpleReflectionStaticFieldsFixture.class)); assertEquals( this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345]", ReflectionToStringBuilder.toString(instance1, null, true, true, SimpleReflectionStaticFieldsFixture.class)); assertEquals( this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345]", this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class)); assertEquals( this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345]", this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class)); } /** * Tests ReflectionToStringBuilder.toString() for statics. */ @Test public void testReflectionStatics() { final ReflectionStaticFieldsFixture instance1 = new ReflectionStaticFieldsFixture(); assertEquals( this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345,instanceString=instanceString,instanceInt=67890]", ReflectionToStringBuilder.toString(instance1, null, false, true, ReflectionStaticFieldsFixture.class)); assertEquals( this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345,staticTransientString=staticTransientString,staticTransientInt=54321,instanceString=instanceString,instanceInt=67890,transientString=transientString,transientInt=98765]", ReflectionToStringBuilder.toString(instance1, null, true, true, ReflectionStaticFieldsFixture.class)); assertEquals( this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345,instanceString=instanceString,instanceInt=67890]", this.toStringWithStatics(instance1, null, ReflectionStaticFieldsFixture.class)); assertEquals( this.toBaseString(instance1) + "[staticString=staticString,staticInt=12345,instanceString=instanceString,instanceInt=67890]", this.toStringWithStatics(instance1, null, ReflectionStaticFieldsFixture.class)); } /** * Tests ReflectionToStringBuilder.toString() for statics. */ @Test public void testInheritedReflectionStatics() { final InheritedReflectionStaticFieldsFixture instance1 = new InheritedReflectionStaticFieldsFixture(); assertEquals( this.toBaseString(instance1) + "[staticString2=staticString2,staticInt2=67890]", ReflectionToStringBuilder.toString(instance1, null, false, true, InheritedReflectionStaticFieldsFixture.class)); assertEquals( this.toBaseString(instance1) + "[staticString2=staticString2,staticInt2=67890,staticString=staticString,staticInt=12345]", ReflectionToStringBuilder.toString(instance1, null, false, true, SimpleReflectionStaticFieldsFixture.class)); assertEquals( this.toBaseString(instance1) + "[staticString2=staticString2,staticInt2=67890,staticString=staticString,staticInt=12345]", this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class)); assertEquals( this.toBaseString(instance1) + "[staticString2=staticString2,staticInt2=67890,staticString=staticString,staticInt=12345]", this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class)); } /** * <p>This method uses reflection to build a suitable * <code>toString</code> value which includes static fields.</p> * * <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private * fields. This means that it will throw a security exception if run * under a security manager, if the permissions are not set up correctly. * It is also not as efficient as testing explicitly. </p> * * <p>Transient fields are not output.</p> * * <p>Superclass fields will be appended up to and including the specified superclass. * A null superclass is treated as <code>java.lang.Object</code>.</p> * * <p>If the style is <code>null</code>, the default * <code>ToStringStyle</code> is used.</p> * * @param object the Object to be output * @param style the style of the <code>toString</code> to create, * may be <code>null</code> * @param reflectUpToClass the superclass to reflect up to (inclusive), * may be <code>null</code> * @return the String result * @throws IllegalArgumentException if the Object is <code>null</code> */ public <T> String toStringWithStatics(final T object, final ToStringStyle style, final Class<? super T> reflectUpToClass) { return ReflectionToStringBuilder.toString(object, style, false, true, reflectUpToClass); } /** * Tests ReflectionToStringBuilder setUpToClass(). */ @Test public void test_setUpToClass_valid() { final Integer val = Integer.valueOf(5); final ReflectionToStringBuilder test = new ReflectionToStringBuilder(val); test.setUpToClass(Number.class); test.toString(); } /** * Tests ReflectionToStringBuilder setUpToClass(). */ @Test(expected=IllegalArgumentException.class) public void test_setUpToClass_invalid() { final Integer val = Integer.valueOf(5); final ReflectionToStringBuilder test = new ReflectionToStringBuilder(val); try { test.setUpToClass(String.class); } finally { test.toString(); } } /** * Tests ReflectionToStringBuilder.toString() for statics. */ class ReflectionStaticFieldsFixture { static final String staticString = "staticString"; static final int staticInt = 12345; static final transient String staticTransientString = "staticTransientString"; static final transient int staticTransientInt = 54321; String instanceString = "instanceString"; int instanceInt = 67890; transient String transientString = "transientString"; transient int transientInt = 98765; } /** * Test fixture for ReflectionToStringBuilder.toString() for statics. */ class SimpleReflectionStaticFieldsFixture { static final String staticString = "staticString"; static final int staticInt = 12345; } /** * Test fixture for ReflectionToStringBuilder.toString() for statics. */ class InheritedReflectionStaticFieldsFixture extends SimpleReflectionStaticFieldsFixture { static final String staticString2 = "staticString2"; static final int staticInt2 = 67890; } @Test public void testReflectionNull() { assertEquals("<null>", ReflectionToStringBuilder.toString(null)); } /** * Points out failure to print anything from appendToString methods using MULTI_LINE_STYLE. * See issue LANG-372. */ class MultiLineTestObject { Integer i = Integer.valueOf(31337); @Override public String toString() { return new ToStringBuilder(this).append("testInt", i).toString(); } } @Test public void testAppendToStringUsingMultiLineStyle() { final MultiLineTestObject obj = new MultiLineTestObject(); final ToStringBuilder testBuilder = new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) .appendToString(obj.toString()); assertEquals(testBuilder.toString().indexOf("testInt=31337"), -1); } }
[ { "be_test_class_file": "org/apache/commons/lang3/builder/ToStringBuilder.java", "be_test_class_name": "org.apache.commons.lang3.builder.ToStringBuilder", "be_test_function_name": "append", "be_test_function_signature": "(Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/commons/lang3/builder/ToStringBuilder;", "line_numbers": [ "848", "849" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/builder/ToStringBuilder.java", "be_test_class_name": "org.apache.commons.lang3.builder.ToStringBuilder", "be_test_function_name": "getDefaultStyle", "be_test_function_signature": "()Lorg/apache/commons/lang3/builder/ToStringStyle;", "line_numbers": [ "117" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/builder/ToStringBuilder.java", "be_test_class_name": "org.apache.commons.lang3.builder.ToStringBuilder", "be_test_function_name": "getObject", "be_test_function_signature": "()Ljava/lang/Object;", "line_numbers": [ "1022" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/builder/ToStringBuilder.java", "be_test_class_name": "org.apache.commons.lang3.builder.ToStringBuilder", "be_test_function_name": "getStringBuffer", "be_test_function_signature": "()Ljava/lang/StringBuffer;", "line_numbers": [ "1031" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/builder/ToStringBuilder.java", "be_test_class_name": "org.apache.commons.lang3.builder.ToStringBuilder", "be_test_function_name": "getStyle", "be_test_function_signature": "()Lorg/apache/commons/lang3/builder/ToStringStyle;", "line_numbers": [ "1043" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/builder/ToStringBuilder.java", "be_test_class_name": "org.apache.commons.lang3.builder.ToStringBuilder", "be_test_function_name": "reflectionToString", "be_test_function_signature": "(Ljava/lang/Object;)Ljava/lang/String;", "line_numbers": [ "152" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/builder/ToStringBuilder.java", "be_test_class_name": "org.apache.commons.lang3.builder.ToStringBuilder", "be_test_function_name": "toString", "be_test_function_signature": "()Ljava/lang/String;", "line_numbers": [ "1058", "1059", "1061", "1063" ], "method_line_rate": 0.75 } ]
public class ErfTest
@Test public void testTwoArgumentErf() { double[] xi = new double[]{-2.0, -1.0, -0.9, -0.1, 0.0, 0.1, 0.9, 1.0, 2.0}; for(double x1 : xi) { for(double x2 : xi) { double a = Erf.erf(x1, x2); double b = Erf.erf(x2) - Erf.erf(x1); double c = Erf.erfc(x1) - Erf.erfc(x2); Assert.assertEquals(a, b, 1E-15); Assert.assertEquals(a, c, 1E-15); } } }
// // Abstract Java Tested Class // package org.apache.commons.math3.special; // // import org.apache.commons.math3.util.FastMath; // // // // public class Erf { // private static final double X_CRIT = 0.4769362762044697; // // private Erf(); // public static double erf(double x); // public static double erfc(double x); // public static double erf(double x1, double x2); // public static double erfInv(final double x); // public static double erfcInv(final double x); // } // // // Abstract Java Test Class // package org.apache.commons.math3.special; // // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.util.FastMath; // import org.junit.Test; // import org.junit.Assert; // // // // public class ErfTest { // // // @Test // public void testErf0(); // @Test // public void testErf1960(); // @Test // public void testErf2576(); // @Test // public void testErf2807(); // @Test // public void testErf3291(); // @Test // public void testLargeValues(); // @Test // public void testErfGnu(); // @Test // public void testErfcGnu(); // @Test // public void testErfcMaple(); // @Test // public void testTwoArgumentErf(); // @Test // public void testErfInvNaN(); // @Test // public void testErfInvInfinite(); // @Test // public void testErfInv(); // @Test // public void testErfcInvNaN(); // @Test // public void testErfcInvInfinite(); // @Test // public void testErfcInv(); // } // You are a professional Java test case writer, please create a test case named `testTwoArgumentErf` for the `Erf` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test the implementation of Erf.erf(double, double) for consistency with results * obtained from Erf.erf(double) and Erf.erfc(double). */
src/test/java/org/apache/commons/math3/special/ErfTest.java
package org.apache.commons.math3.special; import org.apache.commons.math3.util.FastMath;
private Erf(); public static double erf(double x); public static double erfc(double x); public static double erf(double x1, double x2); public static double erfInv(final double x); public static double erfcInv(final double x);
214
testTwoArgumentErf
```java // Abstract Java Tested Class package org.apache.commons.math3.special; import org.apache.commons.math3.util.FastMath; public class Erf { private static final double X_CRIT = 0.4769362762044697; private Erf(); public static double erf(double x); public static double erfc(double x); public static double erf(double x1, double x2); public static double erfInv(final double x); public static double erfcInv(final double x); } // Abstract Java Test Class package org.apache.commons.math3.special; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert; public class ErfTest { @Test public void testErf0(); @Test public void testErf1960(); @Test public void testErf2576(); @Test public void testErf2807(); @Test public void testErf3291(); @Test public void testLargeValues(); @Test public void testErfGnu(); @Test public void testErfcGnu(); @Test public void testErfcMaple(); @Test public void testTwoArgumentErf(); @Test public void testErfInvNaN(); @Test public void testErfInvInfinite(); @Test public void testErfInv(); @Test public void testErfcInvNaN(); @Test public void testErfcInvInfinite(); @Test public void testErfcInv(); } ``` You are a professional Java test case writer, please create a test case named `testTwoArgumentErf` for the `Erf` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test the implementation of Erf.erf(double, double) for consistency with results * obtained from Erf.erf(double) and Erf.erfc(double). */
202
// // Abstract Java Tested Class // package org.apache.commons.math3.special; // // import org.apache.commons.math3.util.FastMath; // // // // public class Erf { // private static final double X_CRIT = 0.4769362762044697; // // private Erf(); // public static double erf(double x); // public static double erfc(double x); // public static double erf(double x1, double x2); // public static double erfInv(final double x); // public static double erfcInv(final double x); // } // // // Abstract Java Test Class // package org.apache.commons.math3.special; // // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.util.FastMath; // import org.junit.Test; // import org.junit.Assert; // // // // public class ErfTest { // // // @Test // public void testErf0(); // @Test // public void testErf1960(); // @Test // public void testErf2576(); // @Test // public void testErf2807(); // @Test // public void testErf3291(); // @Test // public void testLargeValues(); // @Test // public void testErfGnu(); // @Test // public void testErfcGnu(); // @Test // public void testErfcMaple(); // @Test // public void testTwoArgumentErf(); // @Test // public void testErfInvNaN(); // @Test // public void testErfInvInfinite(); // @Test // public void testErfInv(); // @Test // public void testErfcInvNaN(); // @Test // public void testErfcInvInfinite(); // @Test // public void testErfcInv(); // } // You are a professional Java test case writer, please create a test case named `testTwoArgumentErf` for the `Erf` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test the implementation of Erf.erf(double, double) for consistency with results * obtained from Erf.erf(double) and Erf.erfc(double). */ @Test public void testTwoArgumentErf() {
/** * Test the implementation of Erf.erf(double, double) for consistency with results * obtained from Erf.erf(double) and Erf.erfc(double). */
1
org.apache.commons.math3.special.Erf
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.math3.special; import org.apache.commons.math3.util.FastMath; public class Erf { private static final double X_CRIT = 0.4769362762044697; private Erf(); public static double erf(double x); public static double erfc(double x); public static double erf(double x1, double x2); public static double erfInv(final double x); public static double erfcInv(final double x); } // Abstract Java Test Class package org.apache.commons.math3.special; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert; public class ErfTest { @Test public void testErf0(); @Test public void testErf1960(); @Test public void testErf2576(); @Test public void testErf2807(); @Test public void testErf3291(); @Test public void testLargeValues(); @Test public void testErfGnu(); @Test public void testErfcGnu(); @Test public void testErfcMaple(); @Test public void testTwoArgumentErf(); @Test public void testErfInvNaN(); @Test public void testErfInvInfinite(); @Test public void testErfInv(); @Test public void testErfcInvNaN(); @Test public void testErfcInvInfinite(); @Test public void testErfcInv(); } ``` You are a professional Java test case writer, please create a test case named `testTwoArgumentErf` for the `Erf` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test the implementation of Erf.erf(double, double) for consistency with results * obtained from Erf.erf(double) and Erf.erfc(double). */ @Test public void testTwoArgumentErf() { ```
public class Erf
package org.apache.commons.math3.special; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert;
@Test public void testErf0(); @Test public void testErf1960(); @Test public void testErf2576(); @Test public void testErf2807(); @Test public void testErf3291(); @Test public void testLargeValues(); @Test public void testErfGnu(); @Test public void testErfcGnu(); @Test public void testErfcMaple(); @Test public void testTwoArgumentErf(); @Test public void testErfInvNaN(); @Test public void testErfInvInfinite(); @Test public void testErfInv(); @Test public void testErfcInvNaN(); @Test public void testErfcInvInfinite(); @Test public void testErfcInv();
14f3799e2a95d80d2a4d0f74df01159641f615ff0cf80022d7513ef5290f542e
[ "org.apache.commons.math3.special.ErfTest::testTwoArgumentErf" ]
private static final double X_CRIT = 0.4769362762044697;
@Test public void testTwoArgumentErf()
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.special; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert; /** * @version $Id$ */ public class ErfTest { @Test public void testErf0() { double actual = Erf.erf(0.0); double expected = 0.0; Assert.assertEquals(expected, actual, 1.0e-15); Assert.assertEquals(1 - expected, Erf.erfc(0.0), 1.0e-15); } @Test public void testErf1960() { double x = 1.960 / FastMath.sqrt(2.0); double actual = Erf.erf(x); double expected = 0.95; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(x), 1.0e-15); actual = Erf.erf(-x); expected = -expected; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(-x), 1.0e-15); } @Test public void testErf2576() { double x = 2.576 / FastMath.sqrt(2.0); double actual = Erf.erf(x); double expected = 0.99; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(x), 1e-15); actual = Erf.erf(-x); expected = -expected; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(-x), 1.0e-15); } @Test public void testErf2807() { double x = 2.807 / FastMath.sqrt(2.0); double actual = Erf.erf(x); double expected = 0.995; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(x), 1.0e-15); actual = Erf.erf(-x); expected = -expected; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(-x), 1.0e-15); } @Test public void testErf3291() { double x = 3.291 / FastMath.sqrt(2.0); double actual = Erf.erf(x); double expected = 0.999; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - expected, Erf.erfc(x), 1.0e-5); actual = Erf.erf(-x); expected = -expected; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - expected, Erf.erfc(-x), 1.0e-5); } /** * MATH-301, MATH-456 */ @Test public void testLargeValues() { for (int i = 1; i < 200; i*=10) { double result = Erf.erf(i); Assert.assertFalse(Double.isNaN(result)); Assert.assertTrue(result > 0 && result <= 1); result = Erf.erf(-i); Assert.assertFalse(Double.isNaN(result)); Assert.assertTrue(result >= -1 && result < 0); result = Erf.erfc(i); Assert.assertFalse(Double.isNaN(result)); Assert.assertTrue(result >= 0 && result < 1); result = Erf.erfc(-i); Assert.assertFalse(Double.isNaN(result)); Assert.assertTrue(result >= 1 && result <= 2); } Assert.assertEquals(-1, Erf.erf(Double.NEGATIVE_INFINITY), 0); Assert.assertEquals(1, Erf.erf(Double.POSITIVE_INFINITY), 0); Assert.assertEquals(2, Erf.erfc(Double.NEGATIVE_INFINITY), 0); Assert.assertEquals(0, Erf.erfc(Double.POSITIVE_INFINITY), 0); } /** * Compare Erf.erf against reference values computed using GCC 4.2.1 (Apple OSX packaged version) * erfl (extended precision erf). */ @Test public void testErfGnu() { final double tol = 1E-15; final double[] gnuValues = new double[] {-1, -1, -1, -1, -1, -1, -1, -1, -0.99999999999999997848, -0.99999999999999264217, -0.99999999999846254017, -0.99999999980338395581, -0.99999998458274209971, -0.9999992569016276586, -0.99997790950300141459, -0.99959304798255504108, -0.99532226501895273415, -0.96610514647531072711, -0.84270079294971486948, -0.52049987781304653809, 0, 0.52049987781304653809, 0.84270079294971486948, 0.96610514647531072711, 0.99532226501895273415, 0.99959304798255504108, 0.99997790950300141459, 0.9999992569016276586, 0.99999998458274209971, 0.99999999980338395581, 0.99999999999846254017, 0.99999999999999264217, 0.99999999999999997848, 1, 1, 1, 1, 1, 1, 1, 1}; double x = -10d; for (int i = 0; i < 41; i++) { Assert.assertEquals(gnuValues[i], Erf.erf(x), tol); x += 0.5d; } } /** * Compare Erf.erfc against reference values computed using GCC 4.2.1 (Apple OSX packaged version) * erfcl (extended precision erfc). */ @Test public void testErfcGnu() { final double tol = 1E-15; final double[] gnuValues = new double[] { 2, 2, 2, 2, 2, 2, 2, 2, 1.9999999999999999785, 1.9999999999999926422, 1.9999999999984625402, 1.9999999998033839558, 1.9999999845827420998, 1.9999992569016276586, 1.9999779095030014146, 1.9995930479825550411, 1.9953222650189527342, 1.9661051464753107271, 1.8427007929497148695, 1.5204998778130465381, 1, 0.47950012218695346194, 0.15729920705028513051, 0.033894853524689272893, 0.0046777349810472658333, 0.00040695201744495893941, 2.2090496998585441366E-05, 7.4309837234141274516E-07, 1.5417257900280018858E-08, 1.966160441542887477E-10, 1.5374597944280348501E-12, 7.3578479179743980661E-15, 2.1519736712498913103E-17, 3.8421483271206474691E-20, 4.1838256077794144006E-23, 2.7766493860305691016E-26, 1.1224297172982927079E-29, 2.7623240713337714448E-33, 4.1370317465138102353E-37, 3.7692144856548799402E-41, 2.0884875837625447567E-45}; double x = -10d; for (int i = 0; i < 41; i++) { Assert.assertEquals(gnuValues[i], Erf.erfc(x), tol); x += 0.5d; } } /** * Tests erfc against reference data computed using Maple reported in Marsaglia, G,, * "Evaluating the Normal Distribution," Journal of Statistical Software, July, 2004. * http//www.jstatsoft.org/v11/a05/paper */ @Test public void testErfcMaple() { double[][] ref = new double[][] {{0.1, 4.60172162722971e-01}, {1.2, 1.15069670221708e-01}, {2.3, 1.07241100216758e-02}, {3.4, 3.36929265676881e-04}, {4.5, 3.39767312473006e-06}, {5.6, 1.07175902583109e-08}, {6.7, 1.04209769879652e-11}, {7.8, 3.09535877195870e-15}, {8.9, 2.79233437493966e-19}, {10.0, 7.61985302416053e-24}, {11.1, 6.27219439321703e-29}, {12.2, 1.55411978638959e-34}, {13.3, 1.15734162836904e-40}, {14.4, 2.58717592540226e-47}, {15.5, 1.73446079179387e-54}, {16.6, 3.48454651995041e-62} }; for (int i = 0; i < 15; i++) { final double result = 0.5*Erf.erfc(ref[i][0]/Math.sqrt(2)); Assert.assertEquals(ref[i][1], result, 1E-15); TestUtils.assertRelativelyEquals(ref[i][1], result, 1E-13); } } /** * Test the implementation of Erf.erf(double, double) for consistency with results * obtained from Erf.erf(double) and Erf.erfc(double). */ @Test public void testTwoArgumentErf() { double[] xi = new double[]{-2.0, -1.0, -0.9, -0.1, 0.0, 0.1, 0.9, 1.0, 2.0}; for(double x1 : xi) { for(double x2 : xi) { double a = Erf.erf(x1, x2); double b = Erf.erf(x2) - Erf.erf(x1); double c = Erf.erfc(x1) - Erf.erfc(x2); Assert.assertEquals(a, b, 1E-15); Assert.assertEquals(a, c, 1E-15); } } } @Test public void testErfInvNaN() { Assert.assertTrue(Double.isNaN(Erf.erfInv(-1.001))); Assert.assertTrue(Double.isNaN(Erf.erfInv(+1.001))); } @Test public void testErfInvInfinite() { Assert.assertTrue(Double.isInfinite(Erf.erfInv(-1))); Assert.assertTrue(Erf.erfInv(-1) < 0); Assert.assertTrue(Double.isInfinite(Erf.erfInv(+1))); Assert.assertTrue(Erf.erfInv(+1) > 0); } @Test public void testErfInv() { for (double x = -5.9; x < 5.9; x += 0.01) { final double y = Erf.erf(x); final double dydx = 2 * FastMath.exp(-x * x) / FastMath.sqrt(FastMath.PI); Assert.assertEquals(x, Erf.erfInv(y), 1.0e-15 / dydx); } } @Test public void testErfcInvNaN() { Assert.assertTrue(Double.isNaN(Erf.erfcInv(-0.001))); Assert.assertTrue(Double.isNaN(Erf.erfcInv(+2.001))); } @Test public void testErfcInvInfinite() { Assert.assertTrue(Double.isInfinite(Erf.erfcInv(-0))); Assert.assertTrue(Erf.erfcInv( 0) > 0); Assert.assertTrue(Double.isInfinite(Erf.erfcInv(+2))); Assert.assertTrue(Erf.erfcInv(+2) < 0); } @Test public void testErfcInv() { for (double x = -5.85; x < 5.9; x += 0.01) { final double y = Erf.erfc(x); final double dydxAbs = 2 * FastMath.exp(-x * x) / FastMath.sqrt(FastMath.PI); Assert.assertEquals(x, Erf.erfcInv(y), 1.0e-15 / dydxAbs); } } }
[ { "be_test_class_file": "org/apache/commons/math3/special/Erf.java", "be_test_class_name": "org.apache.commons.math3.special.Erf", "be_test_function_name": "erf", "be_test_function_signature": "(D)D", "line_numbers": [ "67", "68", "70", "71" ], "method_line_rate": 0.75 }, { "be_test_class_file": "org/apache/commons/math3/special/Erf.java", "be_test_class_name": "org.apache.commons.math3.special.Erf", "be_test_function_name": "erf", "be_test_function_signature": "(DD)D", "line_numbers": [ "116", "117", "120" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/special/Erf.java", "be_test_class_name": "org.apache.commons.math3.special.Erf", "be_test_function_name": "erfc", "be_test_function_signature": "(D)D", "line_numbers": [ "98", "99", "101", "102" ], "method_line_rate": 0.75 } ]
public class BinaryCodecTest
@Test public void testDecodeObjectException() { try { this.instance.decode(new Object()); } catch (final DecoderException e) { // all is well. return; } fail("Expected DecoderException"); }
// // Abstract Java Tested Class // package org.apache.commons.codec.binary; // // import org.apache.commons.codec.BinaryDecoder; // import org.apache.commons.codec.BinaryEncoder; // import org.apache.commons.codec.DecoderException; // import org.apache.commons.codec.EncoderException; // // // // public class BinaryCodec implements BinaryDecoder, BinaryEncoder { // private static final char[] EMPTY_CHAR_ARRAY = new char[0]; // private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; // private static final int BIT_0 = 1; // private static final int BIT_1 = 0x02; // private static final int BIT_2 = 0x04; // private static final int BIT_3 = 0x08; // private static final int BIT_4 = 0x10; // private static final int BIT_5 = 0x20; // private static final int BIT_6 = 0x40; // private static final int BIT_7 = 0x80; // private static final int[] BITS = {BIT_0, BIT_1, BIT_2, BIT_3, BIT_4, BIT_5, BIT_6, BIT_7}; // // @Override // public byte[] encode(final byte[] raw); // @Override // public Object encode(final Object raw) throws EncoderException; // @Override // public Object decode(final Object ascii) throws DecoderException; // @Override // public byte[] decode(final byte[] ascii); // public byte[] toByteArray(final String ascii); // public static byte[] fromAscii(final char[] ascii); // public static byte[] fromAscii(final byte[] ascii); // private static boolean isEmpty(final byte[] array); // public static byte[] toAsciiBytes(final byte[] raw); // public static char[] toAsciiChars(final byte[] raw); // public static String toAsciiString(final byte[] raw); // } // // // Abstract Java Test Class // package org.apache.commons.codec.binary; // // import static org.junit.Assert.assertEquals; // import static org.junit.Assert.fail; // import java.nio.charset.Charset; // import org.apache.commons.codec.Charsets; // import org.apache.commons.codec.DecoderException; // import org.apache.commons.codec.EncoderException; // import org.junit.After; // import org.junit.Before; // import org.junit.Test; // // // // public class BinaryCodecTest { // private static final Charset CHARSET_UTF8 = Charsets.UTF_8; // private static final int BIT_0 = 0x01; // private static final int BIT_1 = 0x02; // private static final int BIT_2 = 0x04; // private static final int BIT_3 = 0x08; // private static final int BIT_4 = 0x10; // private static final int BIT_5 = 0x20; // private static final int BIT_6 = 0x40; // private static final int BIT_7 = 0x80; // BinaryCodec instance = null; // // @Before // public void setUp() throws Exception; // @After // public void tearDown() throws Exception; // @Test // public void testDecodeObjectException(); // @Test // public void testDecodeObject() throws Exception; // void assertDecodeObject(final byte[] bits, final String encodeMe) throws DecoderException; // @Test // public void testDecodeByteArray(); // @Test // public void testToByteArrayFromString(); // @Test // public void testFromAsciiCharArray(); // @Test // public void testFromAsciiByteArray(); // @Test // public void testEncodeByteArray(); // @Test // public void testToAsciiBytes(); // @Test // public void testToAsciiChars(); // @Test // public void testToAsciiString(); // @Test // public void testEncodeObjectNull() throws Exception; // @Test // public void testEncodeObjectException(); // @Test // public void testEncodeObject() throws Exception; // } // You are a professional Java test case writer, please create a test case named `testDecodeObjectException` for the `BinaryCodec` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests for Object decode(Object) */
src/test/java/org/apache/commons/codec/binary/BinaryCodecTest.java
package org.apache.commons.codec.binary; import org.apache.commons.codec.BinaryDecoder; import org.apache.commons.codec.BinaryEncoder; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.EncoderException;
@Override public byte[] encode(final byte[] raw); @Override public Object encode(final Object raw) throws EncoderException; @Override public Object decode(final Object ascii) throws DecoderException; @Override public byte[] decode(final byte[] ascii); public byte[] toByteArray(final String ascii); public static byte[] fromAscii(final char[] ascii); public static byte[] fromAscii(final byte[] ascii); private static boolean isEmpty(final byte[] array); public static byte[] toAsciiBytes(final byte[] raw); public static char[] toAsciiChars(final byte[] raw); public static String toAsciiString(final byte[] raw);
94
testDecodeObjectException
```java // Abstract Java Tested Class package org.apache.commons.codec.binary; import org.apache.commons.codec.BinaryDecoder; import org.apache.commons.codec.BinaryEncoder; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.EncoderException; public class BinaryCodec implements BinaryDecoder, BinaryEncoder { private static final char[] EMPTY_CHAR_ARRAY = new char[0]; private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private static final int BIT_0 = 1; private static final int BIT_1 = 0x02; private static final int BIT_2 = 0x04; private static final int BIT_3 = 0x08; private static final int BIT_4 = 0x10; private static final int BIT_5 = 0x20; private static final int BIT_6 = 0x40; private static final int BIT_7 = 0x80; private static final int[] BITS = {BIT_0, BIT_1, BIT_2, BIT_3, BIT_4, BIT_5, BIT_6, BIT_7}; @Override public byte[] encode(final byte[] raw); @Override public Object encode(final Object raw) throws EncoderException; @Override public Object decode(final Object ascii) throws DecoderException; @Override public byte[] decode(final byte[] ascii); public byte[] toByteArray(final String ascii); public static byte[] fromAscii(final char[] ascii); public static byte[] fromAscii(final byte[] ascii); private static boolean isEmpty(final byte[] array); public static byte[] toAsciiBytes(final byte[] raw); public static char[] toAsciiChars(final byte[] raw); public static String toAsciiString(final byte[] raw); } // Abstract Java Test Class package org.apache.commons.codec.binary; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.nio.charset.Charset; import org.apache.commons.codec.Charsets; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.EncoderException; import org.junit.After; import org.junit.Before; import org.junit.Test; public class BinaryCodecTest { private static final Charset CHARSET_UTF8 = Charsets.UTF_8; private static final int BIT_0 = 0x01; private static final int BIT_1 = 0x02; private static final int BIT_2 = 0x04; private static final int BIT_3 = 0x08; private static final int BIT_4 = 0x10; private static final int BIT_5 = 0x20; private static final int BIT_6 = 0x40; private static final int BIT_7 = 0x80; BinaryCodec instance = null; @Before public void setUp() throws Exception; @After public void tearDown() throws Exception; @Test public void testDecodeObjectException(); @Test public void testDecodeObject() throws Exception; void assertDecodeObject(final byte[] bits, final String encodeMe) throws DecoderException; @Test public void testDecodeByteArray(); @Test public void testToByteArrayFromString(); @Test public void testFromAsciiCharArray(); @Test public void testFromAsciiByteArray(); @Test public void testEncodeByteArray(); @Test public void testToAsciiBytes(); @Test public void testToAsciiChars(); @Test public void testToAsciiString(); @Test public void testEncodeObjectNull() throws Exception; @Test public void testEncodeObjectException(); @Test public void testEncodeObject() throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testDecodeObjectException` for the `BinaryCodec` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests for Object decode(Object) */
85
// // Abstract Java Tested Class // package org.apache.commons.codec.binary; // // import org.apache.commons.codec.BinaryDecoder; // import org.apache.commons.codec.BinaryEncoder; // import org.apache.commons.codec.DecoderException; // import org.apache.commons.codec.EncoderException; // // // // public class BinaryCodec implements BinaryDecoder, BinaryEncoder { // private static final char[] EMPTY_CHAR_ARRAY = new char[0]; // private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; // private static final int BIT_0 = 1; // private static final int BIT_1 = 0x02; // private static final int BIT_2 = 0x04; // private static final int BIT_3 = 0x08; // private static final int BIT_4 = 0x10; // private static final int BIT_5 = 0x20; // private static final int BIT_6 = 0x40; // private static final int BIT_7 = 0x80; // private static final int[] BITS = {BIT_0, BIT_1, BIT_2, BIT_3, BIT_4, BIT_5, BIT_6, BIT_7}; // // @Override // public byte[] encode(final byte[] raw); // @Override // public Object encode(final Object raw) throws EncoderException; // @Override // public Object decode(final Object ascii) throws DecoderException; // @Override // public byte[] decode(final byte[] ascii); // public byte[] toByteArray(final String ascii); // public static byte[] fromAscii(final char[] ascii); // public static byte[] fromAscii(final byte[] ascii); // private static boolean isEmpty(final byte[] array); // public static byte[] toAsciiBytes(final byte[] raw); // public static char[] toAsciiChars(final byte[] raw); // public static String toAsciiString(final byte[] raw); // } // // // Abstract Java Test Class // package org.apache.commons.codec.binary; // // import static org.junit.Assert.assertEquals; // import static org.junit.Assert.fail; // import java.nio.charset.Charset; // import org.apache.commons.codec.Charsets; // import org.apache.commons.codec.DecoderException; // import org.apache.commons.codec.EncoderException; // import org.junit.After; // import org.junit.Before; // import org.junit.Test; // // // // public class BinaryCodecTest { // private static final Charset CHARSET_UTF8 = Charsets.UTF_8; // private static final int BIT_0 = 0x01; // private static final int BIT_1 = 0x02; // private static final int BIT_2 = 0x04; // private static final int BIT_3 = 0x08; // private static final int BIT_4 = 0x10; // private static final int BIT_5 = 0x20; // private static final int BIT_6 = 0x40; // private static final int BIT_7 = 0x80; // BinaryCodec instance = null; // // @Before // public void setUp() throws Exception; // @After // public void tearDown() throws Exception; // @Test // public void testDecodeObjectException(); // @Test // public void testDecodeObject() throws Exception; // void assertDecodeObject(final byte[] bits, final String encodeMe) throws DecoderException; // @Test // public void testDecodeByteArray(); // @Test // public void testToByteArrayFromString(); // @Test // public void testFromAsciiCharArray(); // @Test // public void testFromAsciiByteArray(); // @Test // public void testEncodeByteArray(); // @Test // public void testToAsciiBytes(); // @Test // public void testToAsciiChars(); // @Test // public void testToAsciiString(); // @Test // public void testEncodeObjectNull() throws Exception; // @Test // public void testEncodeObjectException(); // @Test // public void testEncodeObject() throws Exception; // } // You are a professional Java test case writer, please create a test case named `testDecodeObjectException` for the `BinaryCodec` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests for Object decode(Object) */ // ------------------------------------------------------------------------ // // Test decode(Object) // // ------------------------------------------------------------------------ @Test public void testDecodeObjectException() {
/** * Tests for Object decode(Object) */ // ------------------------------------------------------------------------ // // Test decode(Object) // // ------------------------------------------------------------------------
18
org.apache.commons.codec.binary.BinaryCodec
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.codec.binary; import org.apache.commons.codec.BinaryDecoder; import org.apache.commons.codec.BinaryEncoder; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.EncoderException; public class BinaryCodec implements BinaryDecoder, BinaryEncoder { private static final char[] EMPTY_CHAR_ARRAY = new char[0]; private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private static final int BIT_0 = 1; private static final int BIT_1 = 0x02; private static final int BIT_2 = 0x04; private static final int BIT_3 = 0x08; private static final int BIT_4 = 0x10; private static final int BIT_5 = 0x20; private static final int BIT_6 = 0x40; private static final int BIT_7 = 0x80; private static final int[] BITS = {BIT_0, BIT_1, BIT_2, BIT_3, BIT_4, BIT_5, BIT_6, BIT_7}; @Override public byte[] encode(final byte[] raw); @Override public Object encode(final Object raw) throws EncoderException; @Override public Object decode(final Object ascii) throws DecoderException; @Override public byte[] decode(final byte[] ascii); public byte[] toByteArray(final String ascii); public static byte[] fromAscii(final char[] ascii); public static byte[] fromAscii(final byte[] ascii); private static boolean isEmpty(final byte[] array); public static byte[] toAsciiBytes(final byte[] raw); public static char[] toAsciiChars(final byte[] raw); public static String toAsciiString(final byte[] raw); } // Abstract Java Test Class package org.apache.commons.codec.binary; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.nio.charset.Charset; import org.apache.commons.codec.Charsets; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.EncoderException; import org.junit.After; import org.junit.Before; import org.junit.Test; public class BinaryCodecTest { private static final Charset CHARSET_UTF8 = Charsets.UTF_8; private static final int BIT_0 = 0x01; private static final int BIT_1 = 0x02; private static final int BIT_2 = 0x04; private static final int BIT_3 = 0x08; private static final int BIT_4 = 0x10; private static final int BIT_5 = 0x20; private static final int BIT_6 = 0x40; private static final int BIT_7 = 0x80; BinaryCodec instance = null; @Before public void setUp() throws Exception; @After public void tearDown() throws Exception; @Test public void testDecodeObjectException(); @Test public void testDecodeObject() throws Exception; void assertDecodeObject(final byte[] bits, final String encodeMe) throws DecoderException; @Test public void testDecodeByteArray(); @Test public void testToByteArrayFromString(); @Test public void testFromAsciiCharArray(); @Test public void testFromAsciiByteArray(); @Test public void testEncodeByteArray(); @Test public void testToAsciiBytes(); @Test public void testToAsciiChars(); @Test public void testToAsciiString(); @Test public void testEncodeObjectNull() throws Exception; @Test public void testEncodeObjectException(); @Test public void testEncodeObject() throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testDecodeObjectException` for the `BinaryCodec` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests for Object decode(Object) */ // ------------------------------------------------------------------------ // // Test decode(Object) // // ------------------------------------------------------------------------ @Test public void testDecodeObjectException() { ```
public class BinaryCodec implements BinaryDecoder, BinaryEncoder
package org.apache.commons.codec.binary; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.nio.charset.Charset; import org.apache.commons.codec.Charsets; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.EncoderException; import org.junit.After; import org.junit.Before; import org.junit.Test;
@Before public void setUp() throws Exception; @After public void tearDown() throws Exception; @Test public void testDecodeObjectException(); @Test public void testDecodeObject() throws Exception; void assertDecodeObject(final byte[] bits, final String encodeMe) throws DecoderException; @Test public void testDecodeByteArray(); @Test public void testToByteArrayFromString(); @Test public void testFromAsciiCharArray(); @Test public void testFromAsciiByteArray(); @Test public void testEncodeByteArray(); @Test public void testToAsciiBytes(); @Test public void testToAsciiChars(); @Test public void testToAsciiString(); @Test public void testEncodeObjectNull() throws Exception; @Test public void testEncodeObjectException(); @Test public void testEncodeObject() throws Exception;
15bc9189bd259ea7f3210c38187cd56a761daf8889c0262f05da18f313a964fd
[ "org.apache.commons.codec.binary.BinaryCodecTest::testDecodeObjectException" ]
private static final char[] EMPTY_CHAR_ARRAY = new char[0]; private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private static final int BIT_0 = 1; private static final int BIT_1 = 0x02; private static final int BIT_2 = 0x04; private static final int BIT_3 = 0x08; private static final int BIT_4 = 0x10; private static final int BIT_5 = 0x20; private static final int BIT_6 = 0x40; private static final int BIT_7 = 0x80; private static final int[] BITS = {BIT_0, BIT_1, BIT_2, BIT_3, BIT_4, BIT_5, BIT_6, BIT_7};
@Test public void testDecodeObjectException()
private static final Charset CHARSET_UTF8 = Charsets.UTF_8; private static final int BIT_0 = 0x01; private static final int BIT_1 = 0x02; private static final int BIT_2 = 0x04; private static final int BIT_3 = 0x08; private static final int BIT_4 = 0x10; private static final int BIT_5 = 0x20; private static final int BIT_6 = 0x40; private static final int BIT_7 = 0x80; BinaryCodec instance = null;
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.binary; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.nio.charset.Charset; import org.apache.commons.codec.Charsets; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.EncoderException; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * TestCase for BinaryCodec class. * * @version $Id$ */ public class BinaryCodecTest { private static final Charset CHARSET_UTF8 = Charsets.UTF_8; /** mask with bit zero based index 0 raised */ private static final int BIT_0 = 0x01; /** mask with bit zero based index 0 raised */ private static final int BIT_1 = 0x02; /** mask with bit zero based index 0 raised */ private static final int BIT_2 = 0x04; /** mask with bit zero based index 0 raised */ private static final int BIT_3 = 0x08; /** mask with bit zero based index 0 raised */ private static final int BIT_4 = 0x10; /** mask with bit zero based index 0 raised */ private static final int BIT_5 = 0x20; /** mask with bit zero based index 0 raised */ private static final int BIT_6 = 0x40; /** mask with bit zero based index 0 raised */ private static final int BIT_7 = 0x80; /** an instance of the binary codec */ BinaryCodec instance = null; @Before public void setUp() throws Exception { this.instance = new BinaryCodec(); } @After public void tearDown() throws Exception { this.instance = null; } // ------------------------------------------------------------------------ // // Test decode(Object) // // ------------------------------------------------------------------------ /** * Tests for Object decode(Object) */ @Test public void testDecodeObjectException() { try { this.instance.decode(new Object()); } catch (final DecoderException e) { // all is well. return; } fail("Expected DecoderException"); } /** * Tests for Object decode(Object) */ @Test public void testDecodeObject() throws Exception { byte[] bits; // With a single raw binary bits = new byte[1]; assertDecodeObject(bits, "00000000"); bits = new byte[1]; bits[0] = BIT_0; assertDecodeObject(bits, "00000001"); bits = new byte[1]; bits[0] = BIT_0 | BIT_1; assertDecodeObject(bits, "00000011"); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2; assertDecodeObject(bits, "00000111"); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; assertDecodeObject(bits, "00001111"); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; assertDecodeObject(bits, "00011111"); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; assertDecodeObject(bits, "00111111"); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; assertDecodeObject(bits, "01111111"); bits = new byte[1]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); assertDecodeObject(bits, "11111111"); // With a two raw binaries bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); assertDecodeObject(bits, "0000000011111111"); bits = new byte[2]; bits[1] = BIT_0; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); assertDecodeObject(bits, "0000000111111111"); bits = new byte[2]; bits[1] = BIT_0 | BIT_1; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); assertDecodeObject(bits, "0000001111111111"); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); assertDecodeObject(bits, "0000011111111111"); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); assertDecodeObject(bits, "0000111111111111"); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); assertDecodeObject(bits, "0001111111111111"); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); assertDecodeObject(bits, "0011111111111111"); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); assertDecodeObject(bits, "0111111111111111"); bits = new byte[2]; bits[1] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); assertDecodeObject(bits, "1111111111111111"); assertDecodeObject(new byte[0], null); } // ------------------------------------------------------------------------ // // Test decode(byte[]) // // ------------------------------------------------------------------------ /** * Utility used to assert the encoded and decoded values. * * @param bits * the pre-encoded data * @param encodeMe * data to encode and compare */ void assertDecodeObject(final byte[] bits, final String encodeMe) throws DecoderException { byte[] decoded; decoded = (byte[]) instance.decode(encodeMe); assertEquals(new String(bits), new String(decoded)); if (encodeMe == null) { decoded = instance.decode((byte[]) null); } else { decoded = (byte[]) instance.decode((Object) encodeMe.getBytes(CHARSET_UTF8)); } assertEquals(new String(bits), new String(decoded)); if (encodeMe == null) { decoded = (byte[]) instance.decode((char[]) null); } else { decoded = (byte[]) instance.decode(encodeMe.toCharArray()); } assertEquals(new String(bits), new String(decoded)); } /* * Tests for byte[] decode(byte[]) */ @Test public void testDecodeByteArray() { // With a single raw binary byte[] bits = new byte[1]; byte[] decoded = instance.decode("00000000".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0; decoded = instance.decode("00000001".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1; decoded = instance.decode("00000011".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2; decoded = instance.decode("00000111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; decoded = instance.decode("00001111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; decoded = instance.decode("00011111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; decoded = instance.decode("00111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; decoded = instance.decode("01111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.decode("11111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); // With a two raw binaries bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.decode("0000000011111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.decode("0000000111111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.decode("0000001111111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.decode("0000011111111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.decode("0000111111111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.decode("0001111111111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.decode("0011111111111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.decode("0111111111111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.decode("1111111111111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); } // ------------------------------------------------------------------------ // // Test toByteArray(String) // // ------------------------------------------------------------------------ /* * Tests for byte[] toByteArray(String) */ @Test public void testToByteArrayFromString() { // With a single raw binary byte[] bits = new byte[1]; byte[] decoded = instance.toByteArray("00000000"); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0; decoded = instance.toByteArray("00000001"); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1; decoded = instance.toByteArray("00000011"); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2; decoded = instance.toByteArray("00000111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; decoded = instance.toByteArray("00001111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; decoded = instance.toByteArray("00011111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; decoded = instance.toByteArray("00111111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; decoded = instance.toByteArray("01111111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.toByteArray("11111111"); assertEquals(new String(bits), new String(decoded)); // With a two raw binaries bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.toByteArray("0000000011111111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.toByteArray("0000000111111111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.toByteArray("0000001111111111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.toByteArray("0000011111111111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.toByteArray("0000111111111111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.toByteArray("0001111111111111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.toByteArray("0011111111111111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.toByteArray("0111111111111111"); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = instance.toByteArray("1111111111111111"); assertEquals(new String(bits), new String(decoded)); assertEquals(0, instance.toByteArray((String) null).length); } // ------------------------------------------------------------------------ // // Test fromAscii(char[]) // // ------------------------------------------------------------------------ /* * Tests for byte[] fromAscii(char[]) */ @Test public void testFromAsciiCharArray() { assertEquals(0, BinaryCodec.fromAscii((char[]) null).length); assertEquals(0, BinaryCodec.fromAscii(new char[0]).length); // With a single raw binary byte[] bits = new byte[1]; byte[] decoded = BinaryCodec.fromAscii("00000000".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0; decoded = BinaryCodec.fromAscii("00000001".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1; decoded = BinaryCodec.fromAscii("00000011".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2; decoded = BinaryCodec.fromAscii("00000111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; decoded = BinaryCodec.fromAscii("00001111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; decoded = BinaryCodec.fromAscii("00011111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; decoded = BinaryCodec.fromAscii("00111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; decoded = BinaryCodec.fromAscii("01111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("11111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); // With a two raw binaries bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0000000011111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0000000111111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0000001111111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0000011111111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0000111111111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0001111111111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0011111111111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0111111111111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("1111111111111111".toCharArray()); assertEquals(new String(bits), new String(decoded)); assertEquals(0, BinaryCodec.fromAscii((char[]) null).length); } // ------------------------------------------------------------------------ // // Test fromAscii(byte[]) // // ------------------------------------------------------------------------ /* * Tests for byte[] fromAscii(byte[]) */ @Test public void testFromAsciiByteArray() { assertEquals(0, BinaryCodec.fromAscii((byte[]) null).length); assertEquals(0, BinaryCodec.fromAscii(new byte[0]).length); // With a single raw binary byte[] bits = new byte[1]; byte[] decoded = BinaryCodec.fromAscii("00000000".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0; decoded = BinaryCodec.fromAscii("00000001".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1; decoded = BinaryCodec.fromAscii("00000011".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2; decoded = BinaryCodec.fromAscii("00000111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; decoded = BinaryCodec.fromAscii("00001111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; decoded = BinaryCodec.fromAscii("00011111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; decoded = BinaryCodec.fromAscii("00111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; decoded = BinaryCodec.fromAscii("01111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[1]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("11111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); // With a two raw binaries bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0000000011111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0000000111111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0000001111111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0000011111111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0000111111111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0001111111111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0011111111111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("0111111111111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); bits = new byte[2]; bits[1] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); decoded = BinaryCodec.fromAscii("1111111111111111".getBytes(CHARSET_UTF8)); assertEquals(new String(bits), new String(decoded)); assertEquals(0, BinaryCodec.fromAscii((byte[]) null).length); } // ------------------------------------------------------------------------ // // Test encode(byte[]) // // ------------------------------------------------------------------------ /* * Tests for byte[] encode(byte[]) */ @Test public void testEncodeByteArray() { // With a single raw binary byte[] bits = new byte[1]; String l_encoded = new String(instance.encode(bits)); assertEquals("00000000", l_encoded); bits = new byte[1]; bits[0] = BIT_0; l_encoded = new String(instance.encode(bits)); assertEquals("00000001", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1; l_encoded = new String(instance.encode(bits)); assertEquals("00000011", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2; l_encoded = new String(instance.encode(bits)); assertEquals("00000111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; l_encoded = new String(instance.encode(bits)); assertEquals("00001111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; l_encoded = new String(instance.encode(bits)); assertEquals("00011111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; l_encoded = new String(instance.encode(bits)); assertEquals("00111111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; l_encoded = new String(instance.encode(bits)); assertEquals("01111111", l_encoded); bits = new byte[1]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(instance.encode(bits)); assertEquals("11111111", l_encoded); // With a two raw binaries bits = new byte[2]; l_encoded = new String(instance.encode(bits)); assertEquals("0000000000000000", l_encoded); bits = new byte[2]; bits[0] = BIT_0; l_encoded = new String(instance.encode(bits)); assertEquals("0000000000000001", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1; l_encoded = new String(instance.encode(bits)); assertEquals("0000000000000011", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2; l_encoded = new String(instance.encode(bits)); assertEquals("0000000000000111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; l_encoded = new String(instance.encode(bits)); assertEquals("0000000000001111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; l_encoded = new String(instance.encode(bits)); assertEquals("0000000000011111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; l_encoded = new String(instance.encode(bits)); assertEquals("0000000000111111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; l_encoded = new String(instance.encode(bits)); assertEquals("0000000001111111", l_encoded); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(instance.encode(bits)); assertEquals("0000000011111111", l_encoded); // work on the other byte now bits = new byte[2]; bits[1] = BIT_0; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(instance.encode(bits)); assertEquals("0000000111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(instance.encode(bits)); assertEquals("0000001111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(instance.encode(bits)); assertEquals("0000011111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(instance.encode(bits)); assertEquals("0000111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(instance.encode(bits)); assertEquals("0001111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(instance.encode(bits)); assertEquals("0011111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(instance.encode(bits)); assertEquals("0111111111111111", l_encoded); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); bits[1] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(instance.encode(bits)); assertEquals("1111111111111111", l_encoded); assertEquals(0, instance.encode((byte[]) null).length); } // ------------------------------------------------------------------------ // // Test toAsciiBytes // // ------------------------------------------------------------------------ @Test public void testToAsciiBytes() { // With a single raw binary byte[] bits = new byte[1]; String l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("00000000", l_encoded); bits = new byte[1]; bits[0] = BIT_0; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("00000001", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("00000011", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("00000111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("00001111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("00011111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("00111111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("01111111", l_encoded); bits = new byte[1]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("11111111", l_encoded); // With a two raw binaries bits = new byte[2]; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000000000000000", l_encoded); bits = new byte[2]; bits[0] = BIT_0; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000000000000001", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000000000000011", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000000000000111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000000000001111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000000000011111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000000000111111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000000001111111", l_encoded); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000000011111111", l_encoded); // work on the other byte now bits = new byte[2]; bits[1] = BIT_0; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000000111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000001111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000011111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0000111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0001111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0011111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("0111111111111111", l_encoded); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); bits[1] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiBytes(bits)); assertEquals("1111111111111111", l_encoded); assertEquals(0, BinaryCodec.toAsciiBytes((byte[]) null).length); } // ------------------------------------------------------------------------ // // Test toAsciiChars // // ------------------------------------------------------------------------ @Test public void testToAsciiChars() { // With a single raw binary byte[] bits = new byte[1]; String l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("00000000", l_encoded); bits = new byte[1]; bits[0] = BIT_0; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("00000001", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("00000011", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("00000111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("00001111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("00011111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("00111111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("01111111", l_encoded); bits = new byte[1]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("11111111", l_encoded); // With a two raw binaries bits = new byte[2]; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000000000000000", l_encoded); bits = new byte[2]; bits[0] = BIT_0; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000000000000001", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000000000000011", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000000000000111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000000000001111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000000000011111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000000000111111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000000001111111", l_encoded); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000000011111111", l_encoded); // work on the other byte now bits = new byte[2]; bits[1] = BIT_0; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000000111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000001111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000011111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0000111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0001111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0011111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("0111111111111111", l_encoded); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); bits[1] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String(BinaryCodec.toAsciiChars(bits)); assertEquals("1111111111111111", l_encoded); assertEquals(0, BinaryCodec.toAsciiChars((byte[]) null).length); } // ------------------------------------------------------------------------ // // Test toAsciiString // // ------------------------------------------------------------------------ /** * Tests the toAsciiString(byte[]) method */ @Test public void testToAsciiString() { // With a single raw binary byte[] bits = new byte[1]; String l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("00000000", l_encoded); bits = new byte[1]; bits[0] = BIT_0; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("00000001", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("00000011", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("00000111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("00001111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("00011111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("00111111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("01111111", l_encoded); bits = new byte[1]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("11111111", l_encoded); // With a two raw binaries bits = new byte[2]; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000000000000000", l_encoded); bits = new byte[2]; bits[0] = BIT_0; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000000000000001", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000000000000011", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000000000000111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000000000001111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000000000011111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000000000111111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000000001111111", l_encoded); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000000011111111", l_encoded); // work on the other byte now bits = new byte[2]; bits[1] = BIT_0; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000000111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000001111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000011111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0000111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0001111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0011111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("0111111111111111", l_encoded); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); bits[1] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = BinaryCodec.toAsciiString(bits); assertEquals("1111111111111111", l_encoded); } // ------------------------------------------------------------------------ // // Test encode(Object) // // ------------------------------------------------------------------------ /* * Tests for Object encode(Object) */ @Test public void testEncodeObjectNull() throws Exception { final Object obj = new byte[0]; assertEquals(0, ((char[]) instance.encode(obj)).length); } /* * Tests for Object encode(Object) */ @Test public void testEncodeObjectException() { try { instance.encode(""); } catch (final EncoderException e) { // all is well. return; } fail("Expected EncoderException"); } /* * Tests for Object encode(Object) */ @Test public void testEncodeObject() throws Exception { // With a single raw binary byte[] bits = new byte[1]; String l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("00000000", l_encoded); bits = new byte[1]; bits[0] = BIT_0; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("00000001", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("00000011", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("00000111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("00001111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("00011111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("00111111", l_encoded); bits = new byte[1]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("01111111", l_encoded); bits = new byte[1]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("11111111", l_encoded); // With a two raw binaries bits = new byte[2]; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000000000000000", l_encoded); bits = new byte[2]; bits[0] = BIT_0; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000000000000001", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000000000000011", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000000000000111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000000000001111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000000000011111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000000000111111", l_encoded); bits = new byte[2]; bits[0] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000000001111111", l_encoded); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000000011111111", l_encoded); // work on the other byte now bits = new byte[2]; bits[1] = BIT_0; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000000111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000001111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000011111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0000111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0001111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0011111111111111", l_encoded); bits = new byte[2]; bits[1] = BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("0111111111111111", l_encoded); bits = new byte[2]; bits[0] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); bits[1] = (byte) (BIT_0 | BIT_1 | BIT_2 | BIT_3 | BIT_4 | BIT_5 | BIT_6 | BIT_7); l_encoded = new String((char[]) instance.encode((Object) bits)); assertEquals("1111111111111111", l_encoded); } }
[ { "be_test_class_file": "org/apache/commons/codec/binary/BinaryCodec.java", "be_test_class_name": "org.apache.commons.codec.binary.BinaryCodec", "be_test_function_name": "decode", "be_test_function_signature": "(Ljava/lang/Object;)Ljava/lang/Object;", "line_numbers": [ "116", "117", "119", "120", "122", "123", "125", "126", "128" ], "method_line_rate": 0.5555555555555556 } ]
@SuppressWarnings("serial") public class TestJacksonAnnotationIntrospector extends BaseMapTest
public void testSerializeDeserializeWithJaxbAnnotations() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); JacksonExample ex = new JacksonExample(); QName qname = new QName("urn:hi", "hello"); ex.setQname(qname); ex.setAttributeProperty("attributeValue"); ex.setElementProperty("elementValue"); ex.setWrappedElementProperty(Arrays.asList("wrappedElementValue")); ex.setEnumProperty(EnumExample.VALUE1); StringWriter writer = new StringWriter(); mapper.writeValue(writer, ex); writer.flush(); writer.close(); String json = writer.toString(); JacksonExample readEx = mapper.readValue(json, JacksonExample.class); assertEquals(ex.qname, readEx.qname); assertEquals(ex.attributeProperty, readEx.attributeProperty); assertEquals(ex.elementProperty, readEx.elementProperty); assertEquals(ex.wrappedElementProperty, readEx.wrappedElementProperty); assertEquals(ex.enumProperty, readEx.enumProperty); }
// public void findAndAddVirtualProperties(MapperConfig<?> config, AnnotatedClass ac, // List<BeanPropertyWriter> properties); // protected BeanPropertyWriter _constructVirtualProperty(JsonAppend.Attr attr, // MapperConfig<?> config, AnnotatedClass ac, JavaType type); // protected BeanPropertyWriter _constructVirtualProperty(JsonAppend.Prop prop, // MapperConfig<?> config, AnnotatedClass ac); // @Override // public PropertyName findNameForSerialization(Annotated a); // @Override // since 2.9 // public Boolean hasAsValue(Annotated a); // @Override // since 2.9 // public Boolean hasAnyGetter(Annotated a); // @Override // @Deprecated // since 2.9 // public boolean hasAnyGetterAnnotation(AnnotatedMethod am); // @Override // @Deprecated // since 2.9 // public boolean hasAsValueAnnotation(AnnotatedMethod am); // @Override // public Object findDeserializer(Annotated a); // @Override // public Object findKeyDeserializer(Annotated a); // @Override // public Object findContentDeserializer(Annotated a); // @Override // public Object findDeserializationConverter(Annotated a); // @Override // public Object findDeserializationContentConverter(AnnotatedMember a); // @Override // public JavaType refineDeserializationType(final MapperConfig<?> config, // final Annotated a, final JavaType baseType) throws JsonMappingException; // @Override // @Deprecated // since 2.7 // public Class<?> findDeserializationContentType(Annotated am, JavaType baseContentType); // @Override // @Deprecated // since 2.7 // public Class<?> findDeserializationType(Annotated am, JavaType baseType); // @Override // @Deprecated // since 2.7 // public Class<?> findDeserializationKeyType(Annotated am, JavaType baseKeyType); // @Override // public Object findValueInstantiator(AnnotatedClass ac); // @Override // public Class<?> findPOJOBuilder(AnnotatedClass ac); // @Override // public JsonPOJOBuilder.Value findPOJOBuilderConfig(AnnotatedClass ac); // @Override // public PropertyName findNameForDeserialization(Annotated a); // @Override // public Boolean hasAnySetter(Annotated a); // @Override // public JsonSetter.Value findSetterInfo(Annotated a); // @Override // since 2.9 // public Boolean findMergeInfo(Annotated a); // @Override // @Deprecated // since 2.9 // public boolean hasAnySetterAnnotation(AnnotatedMethod am); // @Override // @Deprecated // since 2.9 // public boolean hasCreatorAnnotation(Annotated a); // @Override // @Deprecated // since 2.9 // public JsonCreator.Mode findCreatorBinding(Annotated a); // @Override // public JsonCreator.Mode findCreatorAnnotation(MapperConfig<?> config, Annotated a); // protected boolean _isIgnorable(Annotated a); // protected Class<?> _classIfExplicit(Class<?> cls); // protected Class<?> _classIfExplicit(Class<?> cls, Class<?> implicit); // protected PropertyName _propertyName(String localName, String namespace); // protected PropertyName _findConstructorName(Annotated a); // @SuppressWarnings("deprecation") // protected TypeResolverBuilder<?> _findTypeResolver(MapperConfig<?> config, // Annotated ann, JavaType baseType); // protected StdTypeResolverBuilder _constructStdTypeResolverBuilder(); // protected StdTypeResolverBuilder _constructNoTypeResolverBuilder(); // private boolean _primitiveAndWrapper(Class<?> baseType, Class<?> refinement); // private boolean _primitiveAndWrapper(JavaType baseType, Class<?> refinement); // } // // // Abstract Java Test Class // package com.fasterxml.jackson.databind.introspect; // // import java.io.IOException; // import java.io.StringWriter; // import java.util.*; // import javax.xml.namespace.QName; // import com.fasterxml.jackson.annotation.*; // import com.fasterxml.jackson.core.JsonGenerator; // import com.fasterxml.jackson.core.JsonParser; // import com.fasterxml.jackson.core.JsonProcessingException; // import com.fasterxml.jackson.databind.*; // import com.fasterxml.jackson.databind.annotation.*; // import com.fasterxml.jackson.databind.deser.std.StdDeserializer; // import com.fasterxml.jackson.databind.introspect.AnnotatedClass; // import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; // import com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder; // import com.fasterxml.jackson.databind.jsontype.impl.StdTypeResolverBuilder; // import com.fasterxml.jackson.databind.type.TypeFactory; // // // // @SuppressWarnings("serial") // public class TestJacksonAnnotationIntrospector // extends BaseMapTest // { // // // public void testSerializeDeserializeWithJaxbAnnotations() throws Exception; // public void testJsonTypeResolver() throws Exception; // public void testEnumHandling() throws Exception; // @JsonSerialize(using=QNameSerializer.class) // public QName getQname(); // @JsonDeserialize(using=QNameDeserializer.class) // public void setQname(QName qname); // @JsonProperty("myattribute") // public String getAttributeProperty(); // @JsonProperty("myattribute") // public void setAttributeProperty(String attributeProperty); // @JsonProperty("myelement") // public String getElementProperty(); // @JsonProperty("myelement") // public void setElementProperty(String elementProperty); // @JsonProperty("mywrapped") // public List<String> getWrappedElementProperty(); // @JsonProperty("mywrapped") // public void setWrappedElementProperty(List<String> wrappedElementProperty); // public EnumExample getEnumProperty(); // public void setEnumProperty(EnumExample enumProperty); // @Override // public void serialize(QName value, JsonGenerator jgen, SerializerProvider provider) // throws IOException, JsonProcessingException; // public QNameDeserializer(); // @Override // public QName deserialize(JsonParser jp, DeserializationContext ctxt) // throws IOException, JsonProcessingException; // @Override // public String[] findEnumValues(Class<?> enumType, Enum<?>[] enumValues, String[] names); // } // You are a professional Java test case writer, please create a test case named `testSerializeDeserializeWithJaxbAnnotations` for the `JacksonAnnotationIntrospector` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * tests getting serializer/deserializer instances. */ /* /********************************************************** /* Unit tests /********************************************************** */
src/test/java/com/fasterxml/jackson/databind/introspect/TestJacksonAnnotationIntrospector.java
package com.fasterxml.jackson.databind.introspect; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.util.*; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.*; import com.fasterxml.jackson.databind.cfg.HandlerInstantiator; import com.fasterxml.jackson.databind.cfg.MapperConfig; import com.fasterxml.jackson.databind.ext.Java7Support; import com.fasterxml.jackson.databind.jsontype.NamedType; import com.fasterxml.jackson.databind.jsontype.TypeIdResolver; import com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder; import com.fasterxml.jackson.databind.jsontype.impl.StdTypeResolverBuilder; import com.fasterxml.jackson.databind.ser.BeanPropertyWriter; import com.fasterxml.jackson.databind.ser.VirtualBeanPropertyWriter; import com.fasterxml.jackson.databind.ser.impl.AttributePropertyWriter; import com.fasterxml.jackson.databind.ser.std.RawSerializer; import com.fasterxml.jackson.databind.type.MapLikeType; import com.fasterxml.jackson.databind.type.TypeFactory; import com.fasterxml.jackson.databind.util.*;
public JacksonAnnotationIntrospector(); @Override public Version version(); protected Object readResolve(); public JacksonAnnotationIntrospector setConstructorPropertiesImpliesCreator(boolean b); @Override public boolean isAnnotationBundle(Annotation ann); @Override @Deprecated // since 2.8 public String findEnumValue(Enum<?> value); @Override // since 2.7 public String[] findEnumValues(Class<?> enumType, Enum<?>[] enumValues, String[] names); @Override public Enum<?> findDefaultEnumValue(Class<Enum<?>> enumCls); @Override public PropertyName findRootName(AnnotatedClass ac); @Override // since 2.8 public JsonIgnoreProperties.Value findPropertyIgnorals(Annotated a); @Override public Boolean isIgnorableType(AnnotatedClass ac); @Override public Object findFilterId(Annotated a); @Override public Object findNamingStrategy(AnnotatedClass ac); @Override public String findClassDescription(AnnotatedClass ac); @Override public VisibilityChecker<?> findAutoDetectVisibility(AnnotatedClass ac, VisibilityChecker<?> checker); @Override public String findImplicitPropertyName(AnnotatedMember m); @Override public List<PropertyName> findPropertyAliases(Annotated m); @Override public boolean hasIgnoreMarker(AnnotatedMember m); @Override public Boolean hasRequiredMarker(AnnotatedMember m); @Override public JsonProperty.Access findPropertyAccess(Annotated m); @Override public String findPropertyDescription(Annotated ann); @Override public Integer findPropertyIndex(Annotated ann); @Override public String findPropertyDefaultValue(Annotated ann); @Override public JsonFormat.Value findFormat(Annotated ann); @Override public ReferenceProperty findReferenceType(AnnotatedMember member); @Override public NameTransformer findUnwrappingNameTransformer(AnnotatedMember member); @Override // since 2.9 public JacksonInject.Value findInjectableValue(AnnotatedMember m); @Override @Deprecated // since 2.9 public Object findInjectableValueId(AnnotatedMember m); @Override public Class<?>[] findViews(Annotated a); @Override // since 2.7 public AnnotatedMethod resolveSetterConflict(MapperConfig<?> config, AnnotatedMethod setter1, AnnotatedMethod setter2); @Override public TypeResolverBuilder<?> findTypeResolver(MapperConfig<?> config, AnnotatedClass ac, JavaType baseType); @Override public TypeResolverBuilder<?> findPropertyTypeResolver(MapperConfig<?> config, AnnotatedMember am, JavaType baseType); @Override public TypeResolverBuilder<?> findPropertyContentTypeResolver(MapperConfig<?> config, AnnotatedMember am, JavaType containerType); @Override public List<NamedType> findSubtypes(Annotated a); @Override public String findTypeName(AnnotatedClass ac); @Override public Boolean isTypeId(AnnotatedMember member); @Override public ObjectIdInfo findObjectIdInfo(Annotated ann); @Override public ObjectIdInfo findObjectReferenceInfo(Annotated ann, ObjectIdInfo objectIdInfo); @Override public Object findSerializer(Annotated a); @Override public Object findKeySerializer(Annotated a); @Override public Object findContentSerializer(Annotated a); @Override public Object findNullSerializer(Annotated a); @Override public JsonInclude.Value findPropertyInclusion(Annotated a); @SuppressWarnings("deprecation") private JsonInclude.Value _refinePropertyInclusion(Annotated a, JsonInclude.Value value); @Override public JsonSerialize.Typing findSerializationTyping(Annotated a); @Override public Object findSerializationConverter(Annotated a); @Override public Object findSerializationContentConverter(AnnotatedMember a); @Override public JavaType refineSerializationType(final MapperConfig<?> config, final Annotated a, final JavaType baseType) throws JsonMappingException; @Override @Deprecated // since 2.7 public Class<?> findSerializationType(Annotated am); @Override @Deprecated // since 2.7 public Class<?> findSerializationKeyType(Annotated am, JavaType baseType); @Override @Deprecated // since 2.7 public Class<?> findSerializationContentType(Annotated am, JavaType baseType); @Override public String[] findSerializationPropertyOrder(AnnotatedClass ac); @Override public Boolean findSerializationSortAlphabetically(Annotated ann); private final Boolean _findSortAlpha(Annotated ann); @Override public void findAndAddVirtualProperties(MapperConfig<?> config, AnnotatedClass ac, List<BeanPropertyWriter> properties); protected BeanPropertyWriter _constructVirtualProperty(JsonAppend.Attr attr, MapperConfig<?> config, AnnotatedClass ac, JavaType type); protected BeanPropertyWriter _constructVirtualProperty(JsonAppend.Prop prop, MapperConfig<?> config, AnnotatedClass ac); @Override public PropertyName findNameForSerialization(Annotated a); @Override // since 2.9 public Boolean hasAsValue(Annotated a); @Override // since 2.9 public Boolean hasAnyGetter(Annotated a); @Override @Deprecated // since 2.9 public boolean hasAnyGetterAnnotation(AnnotatedMethod am); @Override @Deprecated // since 2.9 public boolean hasAsValueAnnotation(AnnotatedMethod am); @Override public Object findDeserializer(Annotated a); @Override public Object findKeyDeserializer(Annotated a); @Override public Object findContentDeserializer(Annotated a); @Override public Object findDeserializationConverter(Annotated a); @Override public Object findDeserializationContentConverter(AnnotatedMember a); @Override public JavaType refineDeserializationType(final MapperConfig<?> config, final Annotated a, final JavaType baseType) throws JsonMappingException; @Override @Deprecated // since 2.7 public Class<?> findDeserializationContentType(Annotated am, JavaType baseContentType); @Override @Deprecated // since 2.7 public Class<?> findDeserializationType(Annotated am, JavaType baseType); @Override @Deprecated // since 2.7 public Class<?> findDeserializationKeyType(Annotated am, JavaType baseKeyType); @Override public Object findValueInstantiator(AnnotatedClass ac); @Override public Class<?> findPOJOBuilder(AnnotatedClass ac); @Override public JsonPOJOBuilder.Value findPOJOBuilderConfig(AnnotatedClass ac); @Override public PropertyName findNameForDeserialization(Annotated a); @Override public Boolean hasAnySetter(Annotated a); @Override public JsonSetter.Value findSetterInfo(Annotated a); @Override // since 2.9 public Boolean findMergeInfo(Annotated a); @Override @Deprecated // since 2.9 public boolean hasAnySetterAnnotation(AnnotatedMethod am); @Override @Deprecated // since 2.9 public boolean hasCreatorAnnotation(Annotated a); @Override @Deprecated // since 2.9 public JsonCreator.Mode findCreatorBinding(Annotated a); @Override public JsonCreator.Mode findCreatorAnnotation(MapperConfig<?> config, Annotated a); protected boolean _isIgnorable(Annotated a); protected Class<?> _classIfExplicit(Class<?> cls); protected Class<?> _classIfExplicit(Class<?> cls, Class<?> implicit); protected PropertyName _propertyName(String localName, String namespace); protected PropertyName _findConstructorName(Annotated a); @SuppressWarnings("deprecation") protected TypeResolverBuilder<?> _findTypeResolver(MapperConfig<?> config, Annotated ann, JavaType baseType); protected StdTypeResolverBuilder _constructStdTypeResolverBuilder(); protected StdTypeResolverBuilder _constructNoTypeResolverBuilder(); private boolean _primitiveAndWrapper(Class<?> baseType, Class<?> refinement); private boolean _primitiveAndWrapper(JavaType baseType, Class<?> refinement);
181
testSerializeDeserializeWithJaxbAnnotations
```java public void findAndAddVirtualProperties(MapperConfig<?> config, AnnotatedClass ac, List<BeanPropertyWriter> properties); protected BeanPropertyWriter _constructVirtualProperty(JsonAppend.Attr attr, MapperConfig<?> config, AnnotatedClass ac, JavaType type); protected BeanPropertyWriter _constructVirtualProperty(JsonAppend.Prop prop, MapperConfig<?> config, AnnotatedClass ac); @Override public PropertyName findNameForSerialization(Annotated a); @Override // since 2.9 public Boolean hasAsValue(Annotated a); @Override // since 2.9 public Boolean hasAnyGetter(Annotated a); @Override @Deprecated // since 2.9 public boolean hasAnyGetterAnnotation(AnnotatedMethod am); @Override @Deprecated // since 2.9 public boolean hasAsValueAnnotation(AnnotatedMethod am); @Override public Object findDeserializer(Annotated a); @Override public Object findKeyDeserializer(Annotated a); @Override public Object findContentDeserializer(Annotated a); @Override public Object findDeserializationConverter(Annotated a); @Override public Object findDeserializationContentConverter(AnnotatedMember a); @Override public JavaType refineDeserializationType(final MapperConfig<?> config, final Annotated a, final JavaType baseType) throws JsonMappingException; @Override @Deprecated // since 2.7 public Class<?> findDeserializationContentType(Annotated am, JavaType baseContentType); @Override @Deprecated // since 2.7 public Class<?> findDeserializationType(Annotated am, JavaType baseType); @Override @Deprecated // since 2.7 public Class<?> findDeserializationKeyType(Annotated am, JavaType baseKeyType); @Override public Object findValueInstantiator(AnnotatedClass ac); @Override public Class<?> findPOJOBuilder(AnnotatedClass ac); @Override public JsonPOJOBuilder.Value findPOJOBuilderConfig(AnnotatedClass ac); @Override public PropertyName findNameForDeserialization(Annotated a); @Override public Boolean hasAnySetter(Annotated a); @Override public JsonSetter.Value findSetterInfo(Annotated a); @Override // since 2.9 public Boolean findMergeInfo(Annotated a); @Override @Deprecated // since 2.9 public boolean hasAnySetterAnnotation(AnnotatedMethod am); @Override @Deprecated // since 2.9 public boolean hasCreatorAnnotation(Annotated a); @Override @Deprecated // since 2.9 public JsonCreator.Mode findCreatorBinding(Annotated a); @Override public JsonCreator.Mode findCreatorAnnotation(MapperConfig<?> config, Annotated a); protected boolean _isIgnorable(Annotated a); protected Class<?> _classIfExplicit(Class<?> cls); protected Class<?> _classIfExplicit(Class<?> cls, Class<?> implicit); protected PropertyName _propertyName(String localName, String namespace); protected PropertyName _findConstructorName(Annotated a); @SuppressWarnings("deprecation") protected TypeResolverBuilder<?> _findTypeResolver(MapperConfig<?> config, Annotated ann, JavaType baseType); protected StdTypeResolverBuilder _constructStdTypeResolverBuilder(); protected StdTypeResolverBuilder _constructNoTypeResolverBuilder(); private boolean _primitiveAndWrapper(Class<?> baseType, Class<?> refinement); private boolean _primitiveAndWrapper(JavaType baseType, Class<?> refinement); } // Abstract Java Test Class package com.fasterxml.jackson.databind.introspect; import java.io.IOException; import java.io.StringWriter; import java.util.*; import javax.xml.namespace.QName; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.*; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.introspect.AnnotatedClass; import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; import com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder; import com.fasterxml.jackson.databind.jsontype.impl.StdTypeResolverBuilder; import com.fasterxml.jackson.databind.type.TypeFactory; @SuppressWarnings("serial") public class TestJacksonAnnotationIntrospector extends BaseMapTest { public void testSerializeDeserializeWithJaxbAnnotations() throws Exception; public void testJsonTypeResolver() throws Exception; public void testEnumHandling() throws Exception; @JsonSerialize(using=QNameSerializer.class) public QName getQname(); @JsonDeserialize(using=QNameDeserializer.class) public void setQname(QName qname); @JsonProperty("myattribute") public String getAttributeProperty(); @JsonProperty("myattribute") public void setAttributeProperty(String attributeProperty); @JsonProperty("myelement") public String getElementProperty(); @JsonProperty("myelement") public void setElementProperty(String elementProperty); @JsonProperty("mywrapped") public List<String> getWrappedElementProperty(); @JsonProperty("mywrapped") public void setWrappedElementProperty(List<String> wrappedElementProperty); public EnumExample getEnumProperty(); public void setEnumProperty(EnumExample enumProperty); @Override public void serialize(QName value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException; public QNameDeserializer(); @Override public QName deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException; @Override public String[] findEnumValues(Class<?> enumType, Enum<?>[] enumValues, String[] names); } ``` You are a professional Java test case writer, please create a test case named `testSerializeDeserializeWithJaxbAnnotations` for the `JacksonAnnotationIntrospector` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * tests getting serializer/deserializer instances. */ /* /********************************************************** /* Unit tests /********************************************************** */
157
// public void findAndAddVirtualProperties(MapperConfig<?> config, AnnotatedClass ac, // List<BeanPropertyWriter> properties); // protected BeanPropertyWriter _constructVirtualProperty(JsonAppend.Attr attr, // MapperConfig<?> config, AnnotatedClass ac, JavaType type); // protected BeanPropertyWriter _constructVirtualProperty(JsonAppend.Prop prop, // MapperConfig<?> config, AnnotatedClass ac); // @Override // public PropertyName findNameForSerialization(Annotated a); // @Override // since 2.9 // public Boolean hasAsValue(Annotated a); // @Override // since 2.9 // public Boolean hasAnyGetter(Annotated a); // @Override // @Deprecated // since 2.9 // public boolean hasAnyGetterAnnotation(AnnotatedMethod am); // @Override // @Deprecated // since 2.9 // public boolean hasAsValueAnnotation(AnnotatedMethod am); // @Override // public Object findDeserializer(Annotated a); // @Override // public Object findKeyDeserializer(Annotated a); // @Override // public Object findContentDeserializer(Annotated a); // @Override // public Object findDeserializationConverter(Annotated a); // @Override // public Object findDeserializationContentConverter(AnnotatedMember a); // @Override // public JavaType refineDeserializationType(final MapperConfig<?> config, // final Annotated a, final JavaType baseType) throws JsonMappingException; // @Override // @Deprecated // since 2.7 // public Class<?> findDeserializationContentType(Annotated am, JavaType baseContentType); // @Override // @Deprecated // since 2.7 // public Class<?> findDeserializationType(Annotated am, JavaType baseType); // @Override // @Deprecated // since 2.7 // public Class<?> findDeserializationKeyType(Annotated am, JavaType baseKeyType); // @Override // public Object findValueInstantiator(AnnotatedClass ac); // @Override // public Class<?> findPOJOBuilder(AnnotatedClass ac); // @Override // public JsonPOJOBuilder.Value findPOJOBuilderConfig(AnnotatedClass ac); // @Override // public PropertyName findNameForDeserialization(Annotated a); // @Override // public Boolean hasAnySetter(Annotated a); // @Override // public JsonSetter.Value findSetterInfo(Annotated a); // @Override // since 2.9 // public Boolean findMergeInfo(Annotated a); // @Override // @Deprecated // since 2.9 // public boolean hasAnySetterAnnotation(AnnotatedMethod am); // @Override // @Deprecated // since 2.9 // public boolean hasCreatorAnnotation(Annotated a); // @Override // @Deprecated // since 2.9 // public JsonCreator.Mode findCreatorBinding(Annotated a); // @Override // public JsonCreator.Mode findCreatorAnnotation(MapperConfig<?> config, Annotated a); // protected boolean _isIgnorable(Annotated a); // protected Class<?> _classIfExplicit(Class<?> cls); // protected Class<?> _classIfExplicit(Class<?> cls, Class<?> implicit); // protected PropertyName _propertyName(String localName, String namespace); // protected PropertyName _findConstructorName(Annotated a); // @SuppressWarnings("deprecation") // protected TypeResolverBuilder<?> _findTypeResolver(MapperConfig<?> config, // Annotated ann, JavaType baseType); // protected StdTypeResolverBuilder _constructStdTypeResolverBuilder(); // protected StdTypeResolverBuilder _constructNoTypeResolverBuilder(); // private boolean _primitiveAndWrapper(Class<?> baseType, Class<?> refinement); // private boolean _primitiveAndWrapper(JavaType baseType, Class<?> refinement); // } // // // Abstract Java Test Class // package com.fasterxml.jackson.databind.introspect; // // import java.io.IOException; // import java.io.StringWriter; // import java.util.*; // import javax.xml.namespace.QName; // import com.fasterxml.jackson.annotation.*; // import com.fasterxml.jackson.core.JsonGenerator; // import com.fasterxml.jackson.core.JsonParser; // import com.fasterxml.jackson.core.JsonProcessingException; // import com.fasterxml.jackson.databind.*; // import com.fasterxml.jackson.databind.annotation.*; // import com.fasterxml.jackson.databind.deser.std.StdDeserializer; // import com.fasterxml.jackson.databind.introspect.AnnotatedClass; // import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; // import com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder; // import com.fasterxml.jackson.databind.jsontype.impl.StdTypeResolverBuilder; // import com.fasterxml.jackson.databind.type.TypeFactory; // // // // @SuppressWarnings("serial") // public class TestJacksonAnnotationIntrospector // extends BaseMapTest // { // // // public void testSerializeDeserializeWithJaxbAnnotations() throws Exception; // public void testJsonTypeResolver() throws Exception; // public void testEnumHandling() throws Exception; // @JsonSerialize(using=QNameSerializer.class) // public QName getQname(); // @JsonDeserialize(using=QNameDeserializer.class) // public void setQname(QName qname); // @JsonProperty("myattribute") // public String getAttributeProperty(); // @JsonProperty("myattribute") // public void setAttributeProperty(String attributeProperty); // @JsonProperty("myelement") // public String getElementProperty(); // @JsonProperty("myelement") // public void setElementProperty(String elementProperty); // @JsonProperty("mywrapped") // public List<String> getWrappedElementProperty(); // @JsonProperty("mywrapped") // public void setWrappedElementProperty(List<String> wrappedElementProperty); // public EnumExample getEnumProperty(); // public void setEnumProperty(EnumExample enumProperty); // @Override // public void serialize(QName value, JsonGenerator jgen, SerializerProvider provider) // throws IOException, JsonProcessingException; // public QNameDeserializer(); // @Override // public QName deserialize(JsonParser jp, DeserializationContext ctxt) // throws IOException, JsonProcessingException; // @Override // public String[] findEnumValues(Class<?> enumType, Enum<?>[] enumValues, String[] names); // } // You are a professional Java test case writer, please create a test case named `testSerializeDeserializeWithJaxbAnnotations` for the `JacksonAnnotationIntrospector` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * tests getting serializer/deserializer instances. */ /* /********************************************************** /* Unit tests /********************************************************** */ public void testSerializeDeserializeWithJaxbAnnotations() throws Exception {
/** * tests getting serializer/deserializer instances. */ /* /********************************************************** /* Unit tests /********************************************************** */
112
com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector
src/test/java
```java public void findAndAddVirtualProperties(MapperConfig<?> config, AnnotatedClass ac, List<BeanPropertyWriter> properties); protected BeanPropertyWriter _constructVirtualProperty(JsonAppend.Attr attr, MapperConfig<?> config, AnnotatedClass ac, JavaType type); protected BeanPropertyWriter _constructVirtualProperty(JsonAppend.Prop prop, MapperConfig<?> config, AnnotatedClass ac); @Override public PropertyName findNameForSerialization(Annotated a); @Override // since 2.9 public Boolean hasAsValue(Annotated a); @Override // since 2.9 public Boolean hasAnyGetter(Annotated a); @Override @Deprecated // since 2.9 public boolean hasAnyGetterAnnotation(AnnotatedMethod am); @Override @Deprecated // since 2.9 public boolean hasAsValueAnnotation(AnnotatedMethod am); @Override public Object findDeserializer(Annotated a); @Override public Object findKeyDeserializer(Annotated a); @Override public Object findContentDeserializer(Annotated a); @Override public Object findDeserializationConverter(Annotated a); @Override public Object findDeserializationContentConverter(AnnotatedMember a); @Override public JavaType refineDeserializationType(final MapperConfig<?> config, final Annotated a, final JavaType baseType) throws JsonMappingException; @Override @Deprecated // since 2.7 public Class<?> findDeserializationContentType(Annotated am, JavaType baseContentType); @Override @Deprecated // since 2.7 public Class<?> findDeserializationType(Annotated am, JavaType baseType); @Override @Deprecated // since 2.7 public Class<?> findDeserializationKeyType(Annotated am, JavaType baseKeyType); @Override public Object findValueInstantiator(AnnotatedClass ac); @Override public Class<?> findPOJOBuilder(AnnotatedClass ac); @Override public JsonPOJOBuilder.Value findPOJOBuilderConfig(AnnotatedClass ac); @Override public PropertyName findNameForDeserialization(Annotated a); @Override public Boolean hasAnySetter(Annotated a); @Override public JsonSetter.Value findSetterInfo(Annotated a); @Override // since 2.9 public Boolean findMergeInfo(Annotated a); @Override @Deprecated // since 2.9 public boolean hasAnySetterAnnotation(AnnotatedMethod am); @Override @Deprecated // since 2.9 public boolean hasCreatorAnnotation(Annotated a); @Override @Deprecated // since 2.9 public JsonCreator.Mode findCreatorBinding(Annotated a); @Override public JsonCreator.Mode findCreatorAnnotation(MapperConfig<?> config, Annotated a); protected boolean _isIgnorable(Annotated a); protected Class<?> _classIfExplicit(Class<?> cls); protected Class<?> _classIfExplicit(Class<?> cls, Class<?> implicit); protected PropertyName _propertyName(String localName, String namespace); protected PropertyName _findConstructorName(Annotated a); @SuppressWarnings("deprecation") protected TypeResolverBuilder<?> _findTypeResolver(MapperConfig<?> config, Annotated ann, JavaType baseType); protected StdTypeResolverBuilder _constructStdTypeResolverBuilder(); protected StdTypeResolverBuilder _constructNoTypeResolverBuilder(); private boolean _primitiveAndWrapper(Class<?> baseType, Class<?> refinement); private boolean _primitiveAndWrapper(JavaType baseType, Class<?> refinement); } // Abstract Java Test Class package com.fasterxml.jackson.databind.introspect; import java.io.IOException; import java.io.StringWriter; import java.util.*; import javax.xml.namespace.QName; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.*; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.introspect.AnnotatedClass; import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; import com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder; import com.fasterxml.jackson.databind.jsontype.impl.StdTypeResolverBuilder; import com.fasterxml.jackson.databind.type.TypeFactory; @SuppressWarnings("serial") public class TestJacksonAnnotationIntrospector extends BaseMapTest { public void testSerializeDeserializeWithJaxbAnnotations() throws Exception; public void testJsonTypeResolver() throws Exception; public void testEnumHandling() throws Exception; @JsonSerialize(using=QNameSerializer.class) public QName getQname(); @JsonDeserialize(using=QNameDeserializer.class) public void setQname(QName qname); @JsonProperty("myattribute") public String getAttributeProperty(); @JsonProperty("myattribute") public void setAttributeProperty(String attributeProperty); @JsonProperty("myelement") public String getElementProperty(); @JsonProperty("myelement") public void setElementProperty(String elementProperty); @JsonProperty("mywrapped") public List<String> getWrappedElementProperty(); @JsonProperty("mywrapped") public void setWrappedElementProperty(List<String> wrappedElementProperty); public EnumExample getEnumProperty(); public void setEnumProperty(EnumExample enumProperty); @Override public void serialize(QName value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException; public QNameDeserializer(); @Override public QName deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException; @Override public String[] findEnumValues(Class<?> enumType, Enum<?>[] enumValues, String[] names); } ``` You are a professional Java test case writer, please create a test case named `testSerializeDeserializeWithJaxbAnnotations` for the `JacksonAnnotationIntrospector` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * tests getting serializer/deserializer instances. */ /* /********************************************************** /* Unit tests /********************************************************** */ public void testSerializeDeserializeWithJaxbAnnotations() throws Exception { ```
public class JacksonAnnotationIntrospector extends AnnotationIntrospector implements java.io.Serializable
package com.fasterxml.jackson.databind.introspect; import java.io.IOException; import java.io.StringWriter; import java.util.*; import javax.xml.namespace.QName; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.*; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.introspect.AnnotatedClass; import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; import com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder; import com.fasterxml.jackson.databind.jsontype.impl.StdTypeResolverBuilder; import com.fasterxml.jackson.databind.type.TypeFactory;
public void testSerializeDeserializeWithJaxbAnnotations() throws Exception; public void testJsonTypeResolver() throws Exception; public void testEnumHandling() throws Exception; @JsonSerialize(using=QNameSerializer.class) public QName getQname(); @JsonDeserialize(using=QNameDeserializer.class) public void setQname(QName qname); @JsonProperty("myattribute") public String getAttributeProperty(); @JsonProperty("myattribute") public void setAttributeProperty(String attributeProperty); @JsonProperty("myelement") public String getElementProperty(); @JsonProperty("myelement") public void setElementProperty(String elementProperty); @JsonProperty("mywrapped") public List<String> getWrappedElementProperty(); @JsonProperty("mywrapped") public void setWrappedElementProperty(List<String> wrappedElementProperty); public EnumExample getEnumProperty(); public void setEnumProperty(EnumExample enumProperty); @Override public void serialize(QName value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException; public QNameDeserializer(); @Override public QName deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException; @Override public String[] findEnumValues(Class<?> enumType, Enum<?>[] enumValues, String[] names);
17f40e9ddf88afc944a8b22771a4fd730762b2c8752c40f079b4a90848fb8bdc
[ "com.fasterxml.jackson.databind.introspect.TestJacksonAnnotationIntrospector::testSerializeDeserializeWithJaxbAnnotations" ]
private static final long serialVersionUID = 1L; @SuppressWarnings("unchecked") private final static Class<? extends Annotation>[] ANNOTATIONS_TO_INFER_SER = (Class<? extends Annotation>[]) new Class<?>[] { JsonSerialize.class, JsonView.class, JsonFormat.class, JsonTypeInfo.class, JsonRawValue.class, JsonUnwrapped.class, JsonBackReference.class, JsonManagedReference.class }; @SuppressWarnings("unchecked") private final static Class<? extends Annotation>[] ANNOTATIONS_TO_INFER_DESER = (Class<? extends Annotation>[]) new Class<?>[] { JsonDeserialize.class, JsonView.class, JsonFormat.class, JsonTypeInfo.class, JsonUnwrapped.class, JsonBackReference.class, JsonManagedReference.class, JsonMerge.class // since 2.9 }; private static final Java7Support _java7Helper; protected transient LRUMap<Class<?>,Boolean> _annotationsInside = new LRUMap<Class<?>,Boolean>(48, 48); protected boolean _cfgConstructorPropertiesImpliesCreator = true;
public void testSerializeDeserializeWithJaxbAnnotations() throws Exception
JacksonDatabind
package com.fasterxml.jackson.databind.introspect; import java.io.IOException; import java.io.StringWriter; import java.util.*; import javax.xml.namespace.QName; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.*; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.introspect.AnnotatedClass; import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; import com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder; import com.fasterxml.jackson.databind.jsontype.impl.StdTypeResolverBuilder; import com.fasterxml.jackson.databind.type.TypeFactory; @SuppressWarnings("serial") public class TestJacksonAnnotationIntrospector extends BaseMapTest { public static enum EnumExample { VALUE1; } public static class JacksonExample { protected String attributeProperty; protected String elementProperty; protected List<String> wrappedElementProperty; protected EnumExample enumProperty; protected QName qname; @JsonSerialize(using=QNameSerializer.class) public QName getQname() { return qname; } @JsonDeserialize(using=QNameDeserializer.class) public void setQname(QName qname) { this.qname = qname; } @JsonProperty("myattribute") public String getAttributeProperty() { return attributeProperty; } @JsonProperty("myattribute") public void setAttributeProperty(String attributeProperty) { this.attributeProperty = attributeProperty; } @JsonProperty("myelement") public String getElementProperty() { return elementProperty; } @JsonProperty("myelement") public void setElementProperty(String elementProperty) { this.elementProperty = elementProperty; } @JsonProperty("mywrapped") public List<String> getWrappedElementProperty() { return wrappedElementProperty; } @JsonProperty("mywrapped") public void setWrappedElementProperty(List<String> wrappedElementProperty) { this.wrappedElementProperty = wrappedElementProperty; } public EnumExample getEnumProperty() { return enumProperty; } public void setEnumProperty(EnumExample enumProperty) { this.enumProperty = enumProperty; } } public static class QNameSerializer extends JsonSerializer<QName> { @Override public void serialize(QName value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeString(value.toString()); } } public static class QNameDeserializer extends StdDeserializer<QName> { public QNameDeserializer() { super(QName.class); } @Override public QName deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { return QName.valueOf(jp.readValueAs(String.class)); } } public static class DummyBuilder extends StdTypeResolverBuilder //<DummyBuilder> { } @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS) @JsonTypeResolver(DummyBuilder.class) static class TypeResolverBean { } // @since 1.7 @JsonIgnoreType static class IgnoredType { } static class IgnoredSubType extends IgnoredType { } // Test to ensure we can override enum settings static class LcEnumIntrospector extends JacksonAnnotationIntrospector { private static final long serialVersionUID = 1L; @Override public String[] findEnumValues(Class<?> enumType, Enum<?>[] enumValues, String[] names) { // kinda sorta wrong, but for testing's sake... for (int i = 0, len = enumValues.length; i < len; ++i) { names[i] = enumValues[i].name().toLowerCase(); } return names; } } /* /********************************************************** /* Unit tests /********************************************************** */ /** * tests getting serializer/deserializer instances. */ public void testSerializeDeserializeWithJaxbAnnotations() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); JacksonExample ex = new JacksonExample(); QName qname = new QName("urn:hi", "hello"); ex.setQname(qname); ex.setAttributeProperty("attributeValue"); ex.setElementProperty("elementValue"); ex.setWrappedElementProperty(Arrays.asList("wrappedElementValue")); ex.setEnumProperty(EnumExample.VALUE1); StringWriter writer = new StringWriter(); mapper.writeValue(writer, ex); writer.flush(); writer.close(); String json = writer.toString(); JacksonExample readEx = mapper.readValue(json, JacksonExample.class); assertEquals(ex.qname, readEx.qname); assertEquals(ex.attributeProperty, readEx.attributeProperty); assertEquals(ex.elementProperty, readEx.elementProperty); assertEquals(ex.wrappedElementProperty, readEx.wrappedElementProperty); assertEquals(ex.enumProperty, readEx.enumProperty); } public void testJsonTypeResolver() throws Exception { ObjectMapper mapper = new ObjectMapper(); JacksonAnnotationIntrospector ai = new JacksonAnnotationIntrospector(); AnnotatedClass ac = AnnotatedClassResolver.resolveWithoutSuperTypes(mapper.getSerializationConfig(), TypeResolverBean.class); JavaType baseType = TypeFactory.defaultInstance().constructType(TypeResolverBean.class); TypeResolverBuilder<?> rb = ai.findTypeResolver(mapper.getDeserializationConfig(), ac, baseType); assertNotNull(rb); assertSame(DummyBuilder.class, rb.getClass()); } public void testEnumHandling() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.setAnnotationIntrospector(new LcEnumIntrospector()); assertEquals("\"value1\"", mapper.writeValueAsString(EnumExample.VALUE1)); EnumExample result = mapper.readValue(quote("value1"), EnumExample.class); assertEquals(EnumExample.VALUE1, result); } }
[ { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "_classIfExplicit", "be_test_function_signature": "(Ljava/lang/Class;)Ljava/lang/Class;", "line_numbers": [ "1360", "1361", "1363" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "_classIfExplicit", "be_test_function_signature": "(Ljava/lang/Class;Ljava/lang/Class;)Ljava/lang/Class;", "line_numbers": [ "1367", "1368" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "_findConstructorName", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Lcom/fasterxml/jackson/databind/PropertyName;", "line_numbers": [ "1383", "1384", "1385", "1387", "1388", "1389", "1390", "1391", "1396" ], "method_line_rate": 0.8888888888888888 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "_findSortAlpha", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Ljava/lang/Boolean;", "line_numbers": [ "892", "895", "896", "898" ], "method_line_rate": 0.75 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "_findTypeResolver", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/cfg/MapperConfig;Lcom/fasterxml/jackson/databind/introspect/Annotated;Lcom/fasterxml/jackson/databind/JavaType;)Lcom/fasterxml/jackson/databind/jsontype/TypeResolverBuilder;", "line_numbers": [ "1409", "1410", "1412", "1413", "1414", "1420", "1422", "1423", "1426", "1427", "1429", "1432", "1433", "1435", "1436", "1438", "1443", "1444", "1445", "1447", "1448", "1449", "1455", "1456", "1458", "1459" ], "method_line_rate": 0.19230769230769232 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "_isIgnorable", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Z", "line_numbers": [ "1346", "1347", "1348", "1350", "1351", "1352", "1353", "1356" ], "method_line_rate": 0.75 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "_refinePropertyInclusion", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;Lcom/fasterxml/jackson/annotation/JsonInclude$Value;)Lcom/fasterxml/jackson/annotation/JsonInclude$Value;", "line_numbers": [ "695", "696", "697", "699", "701", "703", "705", "710" ], "method_line_rate": 0.5 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findAndAddVirtualProperties", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/cfg/MapperConfig;Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;Ljava/util/List;)V", "line_numbers": [ "904", "905", "906", "908", "909", "912", "913", "914", "915", "917", "919", "920", "922", "927", "928", "929", "931", "932", "934", "937" ], "method_line_rate": 0.15 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findAutoDetectVisibility", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;Lcom/fasterxml/jackson/databind/introspect/VisibilityChecker;)Lcom/fasterxml/jackson/databind/introspect/VisibilityChecker;", "line_numbers": [ "323", "324" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findContentDeserializer", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Ljava/lang/Object;", "line_numbers": [ "1089", "1090", "1092", "1093", "1094", "1097" ], "method_line_rate": 0.5 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findContentSerializer", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Ljava/lang/Object;", "line_numbers": [ "655", "656", "658", "659", "660", "663" ], "method_line_rate": 0.5 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findCreatorAnnotation", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/cfg/MapperConfig;Lcom/fasterxml/jackson/databind/introspect/Annotated;)Lcom/fasterxml/jackson/annotation/JsonCreator$Mode;", "line_numbers": [ "1317", "1318", "1319", "1321", "1324", "1325", "1326", "1327", "1330", "1335" ], "method_line_rate": 0.8 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findDefaultEnumValue", "be_test_function_signature": "(Ljava/lang/Class;)Ljava/lang/Enum;", "line_numbers": [ "248" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findDeserializationContentConverter", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/AnnotatedMember;)Ljava/lang/Object;", "line_numbers": [ "1110", "1111" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findDeserializationConverter", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Ljava/lang/Object;", "line_numbers": [ "1103", "1104" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findDeserializer", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Ljava/lang/Object;", "line_numbers": [ "1062", "1063", "1065", "1066", "1067", "1070" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findEnumValues", "be_test_function_signature": "(Ljava/lang/Class;[Ljava/lang/Enum;[Ljava/lang/String;)[Ljava/lang/String;", "line_numbers": [ "206", "207", "208", "209", "211", "212", "213", "215", "216", "217", "219", "220", "222", "225", "226", "227", "228", "229", "230", "234" ], "method_line_rate": 0.45 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findFilterId", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Ljava/lang/Object;", "line_numbers": [ "289", "290", "291", "293", "294", "297" ], "method_line_rate": 0.5 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findFormat", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Lcom/fasterxml/jackson/annotation/JsonFormat$Value;", "line_numbers": [ "412", "413" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findImplicitPropertyName", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/AnnotatedMember;)Ljava/lang/String;", "line_numbers": [ "335", "336" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findInjectableValue", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/AnnotatedMember;)Lcom/fasterxml/jackson/annotation/JacksonInject$Value;", "line_numbers": [ "446", "447", "448", "451", "452", "455", "456", "458", "459", "460", "462", "465", "467" ], "method_line_rate": 0.23076923076923078 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findMergeInfo", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Ljava/lang/Boolean;", "line_numbers": [ "1272", "1273" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findNameForDeserialization", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Lcom/fasterxml/jackson/databind/PropertyName;", "line_numbers": [ "1238", "1239", "1240", "1241", "1243", "1244", "1246", "1249", "1250", "1251", "1253", "1254", "1256" ], "method_line_rate": 0.6923076923076923 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findNameForSerialization", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Lcom/fasterxml/jackson/databind/PropertyName;", "line_numbers": [ "1000", "1001", "1002", "1003", "1005", "1006", "1008", "1010", "1011", "1012", "1014", "1015", "1017" ], "method_line_rate": 0.6923076923076923 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findNamingStrategy", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;)Ljava/lang/Object;", "line_numbers": [ "303", "304" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findNullSerializer", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Ljava/lang/Object;", "line_numbers": [ "669", "670", "672", "673", "674", "677" ], "method_line_rate": 0.8333333333333334 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findObjectIdInfo", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Lcom/fasterxml/jackson/databind/introspect/ObjectIdInfo;", "line_numbers": [ "586", "587", "588", "591", "592" ], "method_line_rate": 0.6 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findPOJOBuilder", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;)Ljava/lang/Class;", "line_numbers": [ "1216", "1217" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findPropertyAccess", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Lcom/fasterxml/jackson/annotation/JsonProperty$Access;", "line_numbers": [ "374", "375", "376", "378" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findPropertyAliases", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Ljava/util/List;", "line_numbers": [ "341", "342", "343", "345", "346", "347", "348", "350", "351", "352", "354" ], "method_line_rate": 0.2727272727272727 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findPropertyContentTypeResolver", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/cfg/MapperConfig;Lcom/fasterxml/jackson/databind/introspect/AnnotatedMember;Lcom/fasterxml/jackson/databind/JavaType;)Lcom/fasterxml/jackson/databind/jsontype/TypeResolverBuilder;", "line_numbers": [ "547", "548", "550" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findPropertyDefaultValue", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Ljava/lang/String;", "line_numbers": [ "401", "402", "403", "405", "407" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findPropertyDescription", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Ljava/lang/String;", "line_numbers": [ "383", "384" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findPropertyIgnorals", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Lcom/fasterxml/jackson/annotation/JsonIgnoreProperties$Value;", "line_numbers": [ "274", "275", "276", "278" ], "method_line_rate": 0.75 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findPropertyInclusion", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Lcom/fasterxml/jackson/annotation/JsonInclude$Value;", "line_numbers": [ "683", "684", "687", "688", "690" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findPropertyIndex", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Ljava/lang/Integer;", "line_numbers": [ "389", "390", "391", "392", "393", "396" ], "method_line_rate": 0.8333333333333334 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findPropertyTypeResolver", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/cfg/MapperConfig;Lcom/fasterxml/jackson/databind/introspect/AnnotatedMember;Lcom/fasterxml/jackson/databind/JavaType;)Lcom/fasterxml/jackson/databind/jsontype/TypeResolverBuilder;", "line_numbers": [ "533", "534", "537" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findReferenceType", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/AnnotatedMember;)Lcom/fasterxml/jackson/databind/AnnotationIntrospector$ReferenceProperty;", "line_numbers": [ "419", "420", "421", "423", "424", "425", "427" ], "method_line_rate": 0.7142857142857143 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findSerializationContentConverter", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/AnnotatedMember;)Ljava/lang/Object;", "line_numbers": [ "728", "729" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findSerializationConverter", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Ljava/lang/Object;", "line_numbers": [ "722", "723" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findSerializationPropertyOrder", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;)[Ljava/lang/String;", "line_numbers": [ "882", "883" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findSerializationSortAlphabetically", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Ljava/lang/Boolean;", "line_numbers": [ "888" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findSerializationTyping", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Lcom/fasterxml/jackson/databind/annotation/JsonSerialize$Typing;", "line_numbers": [ "716", "717" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findSerializer", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Ljava/lang/Object;", "line_numbers": [ "616", "617", "619", "620", "621", "629", "630", "632", "633", "635" ], "method_line_rate": 0.8 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findSetterInfo", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Lcom/fasterxml/jackson/annotation/JsonSetter$Value;", "line_numbers": [ "1267" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findTypeResolver", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/cfg/MapperConfig;Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;Lcom/fasterxml/jackson/databind/JavaType;)Lcom/fasterxml/jackson/databind/jsontype/TypeResolverBuilder;", "line_numbers": [ "522" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findUnwrappingNameTransformer", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/AnnotatedMember;)Lcom/fasterxml/jackson/databind/util/NameTransformer;", "line_numbers": [ "433", "436", "437", "439", "440", "441" ], "method_line_rate": 0.5 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findValueInstantiator", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;)Ljava/lang/Object;", "line_numbers": [ "1208", "1210" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "findViews", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)[Ljava/lang/Class;", "line_numbers": [ "480", "481" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "hasAnyGetter", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Ljava/lang/Boolean;", "line_numbers": [ "1031", "1032", "1033", "1035" ], "method_line_rate": 0.75 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "hasAnySetter", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Ljava/lang/Boolean;", "line_numbers": [ "1261", "1262" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "hasAsValue", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Ljava/lang/Boolean;", "line_numbers": [ "1022", "1023", "1024", "1026" ], "method_line_rate": 0.75 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "hasIgnoreMarker", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/AnnotatedMember;)Z", "line_numbers": [ "359" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "hasRequiredMarker", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/AnnotatedMember;)Ljava/lang/Boolean;", "line_numbers": [ "365", "366", "367", "369" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "isAnnotationBundle", "be_test_function_signature": "(Ljava/lang/annotation/Annotation;)Z", "line_numbers": [ "158", "159", "160", "161", "162", "164" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "isIgnorableType", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;)Ljava/lang/Boolean;", "line_numbers": [ "283", "284" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "isTypeId", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/introspect/AnnotatedMember;)Ljava/lang/Boolean;", "line_numbers": [ "575" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "refineDeserializationType", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/cfg/MapperConfig;Lcom/fasterxml/jackson/databind/introspect/Annotated;Lcom/fasterxml/jackson/databind/JavaType;)Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "1124", "1125", "1127", "1130", "1131", "1134", "1135", "1136", "1140", "1145", "1146", "1147", "1148", "1151", "1152", "1153", "1154", "1158", "1161", "1162", "1164", "1165", "1168", "1169", "1170", "1171", "1175", "1178" ], "method_line_rate": 0.39285714285714285 }, { "be_test_class_file": "com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java", "be_test_class_name": "com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector", "be_test_function_name": "refineSerializationType", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/cfg/MapperConfig;Lcom/fasterxml/jackson/databind/introspect/Annotated;Lcom/fasterxml/jackson/databind/JavaType;)Lcom/fasterxml/jackson/databind/JavaType;", "line_numbers": [ "742", "743", "745", "749", "750", "751", "754", "756", "760", "761", "762", "763", "764", "766", "768", "772", "773", "777", "783", "784", "785", "786", "787", "788", "790", "795", "796", "797", "798", "799", "801", "803", "807", "808", "812", "814", "818", "819", "821", "822", "823", "824", "829", "831", "832", "833", "834", "835", "837", "839", "843", "844", "848", "850", "853" ], "method_line_rate": 0.2 } ]
public class ObjectMapperTest extends BaseMapTest
public void testProps() { ObjectMapper m = new ObjectMapper(); // should have default factory assertNotNull(m.getNodeFactory()); JsonNodeFactory nf = new JsonNodeFactory(true); m.setNodeFactory(nf); assertNull(m.getInjectableValues()); assertSame(nf, m.getNodeFactory()); }
// throws IOException; // protected JsonNode _readTreeAndClose(JsonParser p0) throws IOException; // protected Object _unwrapAndDeserialize(JsonParser p, DeserializationContext ctxt, // DeserializationConfig config, // JavaType rootType, JsonDeserializer<Object> deser) // throws IOException; // protected DefaultDeserializationContext createDeserializationContext(JsonParser p, // DeserializationConfig cfg); // protected JsonToken _initForReading(JsonParser p, JavaType targetType) throws IOException; // @Deprecated // since 2.9, use method that takes JavaType too // protected JsonToken _initForReading(JsonParser p) throws IOException; // protected final void _verifyNoTrailingTokens(JsonParser p, DeserializationContext ctxt, // JavaType bindType) // throws IOException; // protected JsonDeserializer<Object> _findRootDeserializer(DeserializationContext ctxt, // JavaType valueType) // throws JsonMappingException; // protected void _verifySchemaType(FormatSchema schema); // public DefaultTypeResolverBuilder(DefaultTyping t); // @Override // public TypeDeserializer buildTypeDeserializer(DeserializationConfig config, // JavaType baseType, Collection<NamedType> subtypes); // @Override // public TypeSerializer buildTypeSerializer(SerializationConfig config, // JavaType baseType, Collection<NamedType> subtypes); // public boolean useForType(JavaType t); // @Override // public Version getMapperVersion(); // @SuppressWarnings("unchecked") // @Override // public <C extends ObjectCodec> C getOwner(); // @Override // public TypeFactory getTypeFactory(); // @Override // public boolean isEnabled(MapperFeature f); // @Override // public boolean isEnabled(DeserializationFeature f); // @Override // public boolean isEnabled(SerializationFeature f); // @Override // public boolean isEnabled(JsonFactory.Feature f); // @Override // public boolean isEnabled(JsonParser.Feature f); // @Override // public boolean isEnabled(JsonGenerator.Feature f); // @Override // public MutableConfigOverride configOverride(Class<?> type); // @Override // public void addDeserializers(Deserializers d); // @Override // public void addKeyDeserializers(KeyDeserializers d); // @Override // public void addBeanDeserializerModifier(BeanDeserializerModifier modifier); // @Override // public void addSerializers(Serializers s); // @Override // public void addKeySerializers(Serializers s); // @Override // public void addBeanSerializerModifier(BeanSerializerModifier modifier); // @Override // public void addAbstractTypeResolver(AbstractTypeResolver resolver); // @Override // public void addTypeModifier(TypeModifier modifier); // @Override // public void addValueInstantiators(ValueInstantiators instantiators); // @Override // public void setClassIntrospector(ClassIntrospector ci); // @Override // public void insertAnnotationIntrospector(AnnotationIntrospector ai); // @Override // public void appendAnnotationIntrospector(AnnotationIntrospector ai); // @Override // public void registerSubtypes(Class<?>... subtypes); // @Override // public void registerSubtypes(NamedType... subtypes); // @Override // public void registerSubtypes(Collection<Class<?>> subtypes); // @Override // public void setMixInAnnotations(Class<?> target, Class<?> mixinSource); // @Override // public void addDeserializationProblemHandler(DeserializationProblemHandler handler); // @Override // public void setNamingStrategy(PropertyNamingStrategy naming); // @Override // public ServiceLoader<T> run(); // } // // // Abstract Java Test Class // package com.fasterxml.jackson.databind; // // import java.io.*; // import java.util.*; // import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; // import com.fasterxml.jackson.annotation.JsonInclude; // import com.fasterxml.jackson.annotation.JsonSetter; // import com.fasterxml.jackson.annotation.Nulls; // import com.fasterxml.jackson.core.*; // import com.fasterxml.jackson.core.util.MinimalPrettyPrinter; // import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; // import com.fasterxml.jackson.databind.introspect.VisibilityChecker; // import com.fasterxml.jackson.databind.node.*; // // // // public class ObjectMapperTest extends BaseMapTest // { // final ObjectMapper MAPPER = new ObjectMapper(); // // public void testFactorFeatures(); // public void testGeneratorFeatures(); // public void testParserFeatures(); // public void testCopy() throws Exception; // public void testCopyOfConfigOverrides() throws Exception; // public void testFailedCopy() throws Exception; // public void testAnnotationIntrospectorCopyin(); // public void testProps(); // public void testConfigForPropertySorting() throws Exception; // public void testJsonFactoryLinkage(); // public void testProviderConfig() throws Exception; // public void testCustomDefaultPrettyPrinter() throws Exception; // public void testNonSerializabilityOfObject(); // public void testEmptyBeanSerializability(); // public void testSerializerProviderAccess() throws Exception; // public void testCopyOfParserFeatures() throws Exception; // public void testDataOutputViaMapper() throws Exception; // @SuppressWarnings("unchecked") // public void testDataInputViaMapper() throws Exception; // public void setX(int v); // protected Bean(); // public Bean(int v); // public FooPrettyPrinter(); // @Override // public void writeArrayValueSeparator(JsonGenerator g) throws IOException; // } // You are a professional Java test case writer, please create a test case named `testProps` for the `ObjectMapper` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Test methods, other /********************************************************** */
src/test/java/com/fasterxml/jackson/databind/ObjectMapperTest.java
package com.fasterxml.jackson.databind; import java.io.*; import java.lang.reflect.Type; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.text.DateFormat; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReference; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.io.CharacterEscapes; import com.fasterxml.jackson.core.io.SegmentedStringWriter; import com.fasterxml.jackson.core.type.ResolvedType; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.util.*; import com.fasterxml.jackson.databind.cfg.*; import com.fasterxml.jackson.databind.deser.*; import com.fasterxml.jackson.databind.exc.MismatchedInputException; import com.fasterxml.jackson.databind.introspect.*; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper; import com.fasterxml.jackson.databind.jsontype.*; import com.fasterxml.jackson.databind.jsontype.impl.StdSubtypeResolver; import com.fasterxml.jackson.databind.jsontype.impl.StdTypeResolverBuilder; import com.fasterxml.jackson.databind.node.*; import com.fasterxml.jackson.databind.ser.*; import com.fasterxml.jackson.databind.type.*; import com.fasterxml.jackson.databind.util.ClassUtil; import com.fasterxml.jackson.databind.util.RootNameLookup; import com.fasterxml.jackson.databind.util.StdDateFormat; import com.fasterxml.jackson.databind.util.TokenBuffer;
public ObjectMapper(); public ObjectMapper(JsonFactory jf); protected ObjectMapper(ObjectMapper src); public ObjectMapper(JsonFactory jf, DefaultSerializerProvider sp, DefaultDeserializationContext dc); protected ClassIntrospector defaultClassIntrospector(); public ObjectMapper copy(); protected void _checkInvalidCopy(Class<?> exp); protected ObjectReader _newReader(DeserializationConfig config); protected ObjectReader _newReader(DeserializationConfig config, JavaType valueType, Object valueToUpdate, FormatSchema schema, InjectableValues injectableValues); protected ObjectWriter _newWriter(SerializationConfig config); protected ObjectWriter _newWriter(SerializationConfig config, FormatSchema schema); protected ObjectWriter _newWriter(SerializationConfig config, JavaType rootType, PrettyPrinter pp); @Override public Version version(); public ObjectMapper registerModule(Module module); public ObjectMapper registerModules(Module... modules); public ObjectMapper registerModules(Iterable<? extends Module> modules); public Set<Object> getRegisteredModuleIds(); public static List<Module> findModules(); public static List<Module> findModules(ClassLoader classLoader); private static <T> ServiceLoader<T> secureGetServiceLoader(final Class<T> clazz, final ClassLoader classLoader); public ObjectMapper findAndRegisterModules(); public SerializationConfig getSerializationConfig(); public DeserializationConfig getDeserializationConfig(); public DeserializationContext getDeserializationContext(); public ObjectMapper setSerializerFactory(SerializerFactory f); public SerializerFactory getSerializerFactory(); public ObjectMapper setSerializerProvider(DefaultSerializerProvider p); public SerializerProvider getSerializerProvider(); public SerializerProvider getSerializerProviderInstance(); public ObjectMapper setMixIns(Map<Class<?>, Class<?>> sourceMixins); public ObjectMapper addMixIn(Class<?> target, Class<?> mixinSource); public ObjectMapper setMixInResolver(ClassIntrospector.MixInResolver resolver); public Class<?> findMixInClassFor(Class<?> cls); public int mixInCount(); @Deprecated public void setMixInAnnotations(Map<Class<?>, Class<?>> sourceMixins); @Deprecated public final void addMixInAnnotations(Class<?> target, Class<?> mixinSource); public VisibilityChecker<?> getVisibilityChecker(); public ObjectMapper setVisibility(VisibilityChecker<?> vc); public ObjectMapper setVisibility(PropertyAccessor forMethod, JsonAutoDetect.Visibility visibility); public SubtypeResolver getSubtypeResolver(); public ObjectMapper setSubtypeResolver(SubtypeResolver str); public ObjectMapper setAnnotationIntrospector(AnnotationIntrospector ai); public ObjectMapper setAnnotationIntrospectors(AnnotationIntrospector serializerAI, AnnotationIntrospector deserializerAI); public ObjectMapper setPropertyNamingStrategy(PropertyNamingStrategy s); public PropertyNamingStrategy getPropertyNamingStrategy(); public ObjectMapper setDefaultPrettyPrinter(PrettyPrinter pp); @Deprecated public void setVisibilityChecker(VisibilityChecker<?> vc); public ObjectMapper setSerializationInclusion(JsonInclude.Include incl); @Deprecated public ObjectMapper setPropertyInclusion(JsonInclude.Value incl); public ObjectMapper setDefaultPropertyInclusion(JsonInclude.Value incl); public ObjectMapper setDefaultPropertyInclusion(JsonInclude.Include incl); public ObjectMapper setDefaultSetterInfo(JsonSetter.Value v); public ObjectMapper setDefaultVisibility(JsonAutoDetect.Value vis); public ObjectMapper setDefaultMergeable(Boolean b); public ObjectMapper enableDefaultTyping(); public ObjectMapper enableDefaultTyping(DefaultTyping dti); public ObjectMapper enableDefaultTyping(DefaultTyping applicability, JsonTypeInfo.As includeAs); public ObjectMapper enableDefaultTypingAsProperty(DefaultTyping applicability, String propertyName); public ObjectMapper disableDefaultTyping(); public ObjectMapper setDefaultTyping(TypeResolverBuilder<?> typer); public void registerSubtypes(Class<?>... classes); public void registerSubtypes(NamedType... types); public void registerSubtypes(Collection<Class<?>> subtypes); public MutableConfigOverride configOverride(Class<?> type); public TypeFactory getTypeFactory(); public ObjectMapper setTypeFactory(TypeFactory f); public JavaType constructType(Type t); public JsonNodeFactory getNodeFactory(); public ObjectMapper setNodeFactory(JsonNodeFactory f); public ObjectMapper addHandler(DeserializationProblemHandler h); public ObjectMapper clearProblemHandlers(); public ObjectMapper setConfig(DeserializationConfig config); @Deprecated public void setFilters(FilterProvider filterProvider); public ObjectMapper setFilterProvider(FilterProvider filterProvider); public ObjectMapper setBase64Variant(Base64Variant v); public ObjectMapper setConfig(SerializationConfig config); @Override public JsonFactory getFactory(); @Deprecated @Override public JsonFactory getJsonFactory(); public ObjectMapper setDateFormat(DateFormat dateFormat); public DateFormat getDateFormat(); public Object setHandlerInstantiator(HandlerInstantiator hi); public ObjectMapper setInjectableValues(InjectableValues injectableValues); public InjectableValues getInjectableValues(); public ObjectMapper setLocale(Locale l); public ObjectMapper setTimeZone(TimeZone tz); public boolean isEnabled(MapperFeature f); public ObjectMapper configure(MapperFeature f, boolean state); public ObjectMapper enable(MapperFeature... f); public ObjectMapper disable(MapperFeature... f); public boolean isEnabled(SerializationFeature f); public ObjectMapper configure(SerializationFeature f, boolean state); public ObjectMapper enable(SerializationFeature f); public ObjectMapper enable(SerializationFeature first, SerializationFeature... f); public ObjectMapper disable(SerializationFeature f); public ObjectMapper disable(SerializationFeature first, SerializationFeature... f); public boolean isEnabled(DeserializationFeature f); public ObjectMapper configure(DeserializationFeature f, boolean state); public ObjectMapper enable(DeserializationFeature feature); public ObjectMapper enable(DeserializationFeature first, DeserializationFeature... f); public ObjectMapper disable(DeserializationFeature feature); public ObjectMapper disable(DeserializationFeature first, DeserializationFeature... f); public boolean isEnabled(JsonParser.Feature f); public ObjectMapper configure(JsonParser.Feature f, boolean state); public ObjectMapper enable(JsonParser.Feature... features); public ObjectMapper disable(JsonParser.Feature... features); public boolean isEnabled(JsonGenerator.Feature f); public ObjectMapper configure(JsonGenerator.Feature f, boolean state); public ObjectMapper enable(JsonGenerator.Feature... features); public ObjectMapper disable(JsonGenerator.Feature... features); public boolean isEnabled(JsonFactory.Feature f); @Override @SuppressWarnings("unchecked") public <T> T readValue(JsonParser p, Class<T> valueType) throws IOException, JsonParseException, JsonMappingException; @Override @SuppressWarnings("unchecked") public <T> T readValue(JsonParser p, TypeReference<?> valueTypeRef) throws IOException, JsonParseException, JsonMappingException; @Override @SuppressWarnings("unchecked") public final <T> T readValue(JsonParser p, ResolvedType valueType) throws IOException, JsonParseException, JsonMappingException; @SuppressWarnings("unchecked") public <T> T readValue(JsonParser p, JavaType valueType) throws IOException, JsonParseException, JsonMappingException; @Override public <T extends TreeNode> T readTree(JsonParser p) throws IOException, JsonProcessingException; @Override public <T> MappingIterator<T> readValues(JsonParser p, ResolvedType valueType) throws IOException, JsonProcessingException; public <T> MappingIterator<T> readValues(JsonParser p, JavaType valueType) throws IOException, JsonProcessingException; @Override public <T> MappingIterator<T> readValues(JsonParser p, Class<T> valueType) throws IOException, JsonProcessingException; @Override public <T> MappingIterator<T> readValues(JsonParser p, TypeReference<?> valueTypeRef) throws IOException, JsonProcessingException; public JsonNode readTree(InputStream in) throws IOException; public JsonNode readTree(Reader r) throws IOException; public JsonNode readTree(String content) throws IOException; public JsonNode readTree(byte[] content) throws IOException; public JsonNode readTree(File file) throws IOException, JsonProcessingException; public JsonNode readTree(URL source) throws IOException; @Override public void writeValue(JsonGenerator g, Object value) throws IOException, JsonGenerationException, JsonMappingException; @Override public void writeTree(JsonGenerator jgen, TreeNode rootNode) throws IOException, JsonProcessingException; public void writeTree(JsonGenerator jgen, JsonNode rootNode) throws IOException, JsonProcessingException; @Override public ObjectNode createObjectNode(); @Override public ArrayNode createArrayNode(); @Override public JsonParser treeAsTokens(TreeNode n); @SuppressWarnings("unchecked") @Override public <T> T treeToValue(TreeNode n, Class<T> valueType) throws JsonProcessingException; @SuppressWarnings({ "unchecked", "resource" }) public <T extends JsonNode> T valueToTree(Object fromValue) throws IllegalArgumentException; public boolean canSerialize(Class<?> type); public boolean canSerialize(Class<?> type, AtomicReference<Throwable> cause); public boolean canDeserialize(JavaType type); public boolean canDeserialize(JavaType type, AtomicReference<Throwable> cause); @SuppressWarnings("unchecked") public <T> T readValue(File src, Class<T> valueType) throws IOException, JsonParseException, JsonMappingException; @SuppressWarnings({ "unchecked", "rawtypes" }) public <T> T readValue(File src, TypeReference valueTypeRef) throws IOException, JsonParseException, JsonMappingException; @SuppressWarnings("unchecked") public <T> T readValue(File src, JavaType valueType) throws IOException, JsonParseException, JsonMappingException; @SuppressWarnings("unchecked") public <T> T readValue(URL src, Class<T> valueType) throws IOException, JsonParseException, JsonMappingException; @SuppressWarnings({ "unchecked", "rawtypes" }) public <T> T readValue(URL src, TypeReference valueTypeRef) throws IOException, JsonParseException, JsonMappingException; @SuppressWarnings("unchecked") public <T> T readValue(URL src, JavaType valueType) throws IOException, JsonParseException, JsonMappingException; @SuppressWarnings("unchecked") public <T> T readValue(String content, Class<T> valueType) throws IOException, JsonParseException, JsonMappingException; @SuppressWarnings({ "unchecked", "rawtypes" }) public <T> T readValue(String content, TypeReference valueTypeRef) throws IOException, JsonParseException, JsonMappingException; @SuppressWarnings("unchecked") public <T> T readValue(String content, JavaType valueType) throws IOException, JsonParseException, JsonMappingException; @SuppressWarnings("unchecked") public <T> T readValue(Reader src, Class<T> valueType) throws IOException, JsonParseException, JsonMappingException; @SuppressWarnings({ "unchecked", "rawtypes" }) public <T> T readValue(Reader src, TypeReference valueTypeRef) throws IOException, JsonParseException, JsonMappingException; @SuppressWarnings("unchecked") public <T> T readValue(Reader src, JavaType valueType) throws IOException, JsonParseException, JsonMappingException; @SuppressWarnings("unchecked") public <T> T readValue(InputStream src, Class<T> valueType) throws IOException, JsonParseException, JsonMappingException; @SuppressWarnings({ "unchecked", "rawtypes" }) public <T> T readValue(InputStream src, TypeReference valueTypeRef) throws IOException, JsonParseException, JsonMappingException; @SuppressWarnings("unchecked") public <T> T readValue(InputStream src, JavaType valueType) throws IOException, JsonParseException, JsonMappingException; @SuppressWarnings("unchecked") public <T> T readValue(byte[] src, Class<T> valueType) throws IOException, JsonParseException, JsonMappingException; @SuppressWarnings("unchecked") public <T> T readValue(byte[] src, int offset, int len, Class<T> valueType) throws IOException, JsonParseException, JsonMappingException; @SuppressWarnings({ "unchecked", "rawtypes" }) public <T> T readValue(byte[] src, TypeReference valueTypeRef) throws IOException, JsonParseException, JsonMappingException; @SuppressWarnings({ "unchecked", "rawtypes" }) public <T> T readValue(byte[] src, int offset, int len, TypeReference valueTypeRef) throws IOException, JsonParseException, JsonMappingException; @SuppressWarnings("unchecked") public <T> T readValue(byte[] src, JavaType valueType) throws IOException, JsonParseException, JsonMappingException; @SuppressWarnings("unchecked") public <T> T readValue(byte[] src, int offset, int len, JavaType valueType) throws IOException, JsonParseException, JsonMappingException; @SuppressWarnings("unchecked") public <T> T readValue(DataInput src, Class<T> valueType) throws IOException; @SuppressWarnings("unchecked") public <T> T readValue(DataInput src, JavaType valueType) 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(DataOutput out, Object value) throws IOException; public void writeValue(Writer w, Object value) throws IOException, JsonGenerationException, JsonMappingException; @SuppressWarnings("resource") public String writeValueAsString(Object value) throws JsonProcessingException; @SuppressWarnings("resource") public byte[] writeValueAsBytes(Object value) throws JsonProcessingException; public ObjectWriter writer(); public ObjectWriter writer(SerializationFeature feature); public ObjectWriter writer(SerializationFeature first, SerializationFeature... other); public ObjectWriter writer(DateFormat df); public ObjectWriter writerWithView(Class<?> serializationView); public ObjectWriter writerFor(Class<?> rootType); public ObjectWriter writerFor(TypeReference<?> rootType); public ObjectWriter writerFor(JavaType rootType); public ObjectWriter writer(PrettyPrinter pp); public ObjectWriter writerWithDefaultPrettyPrinter(); public ObjectWriter writer(FilterProvider filterProvider); public ObjectWriter writer(FormatSchema schema); public ObjectWriter writer(Base64Variant defaultBase64); public ObjectWriter writer(CharacterEscapes escapes); public ObjectWriter writer(ContextAttributes attrs); @Deprecated public ObjectWriter writerWithType(Class<?> rootType); @Deprecated public ObjectWriter writerWithType(TypeReference<?> rootType); @Deprecated public ObjectWriter writerWithType(JavaType rootType); public ObjectReader reader(); public ObjectReader reader(DeserializationFeature feature); public ObjectReader reader(DeserializationFeature first, DeserializationFeature... other); public ObjectReader readerForUpdating(Object valueToUpdate); public ObjectReader readerFor(JavaType type); public ObjectReader readerFor(Class<?> type); public ObjectReader readerFor(TypeReference<?> type); public ObjectReader reader(JsonNodeFactory f); public ObjectReader reader(FormatSchema schema); public ObjectReader reader(InjectableValues injectableValues); public ObjectReader readerWithView(Class<?> view); public ObjectReader reader(Base64Variant defaultBase64); public ObjectReader reader(ContextAttributes attrs); @Deprecated public ObjectReader reader(JavaType type); @Deprecated public ObjectReader reader(Class<?> type); @Deprecated public ObjectReader reader(TypeReference<?> type); @SuppressWarnings("unchecked") public <T> T convertValue(Object fromValue, Class<T> toValueType) throws IllegalArgumentException; @SuppressWarnings("unchecked") public <T> T convertValue(Object fromValue, TypeReference<?> toValueTypeRef) throws IllegalArgumentException; @SuppressWarnings("unchecked") public <T> T convertValue(Object fromValue, JavaType toValueType) throws IllegalArgumentException; @SuppressWarnings("resource") protected Object _convert(Object fromValue, JavaType toValueType) throws IllegalArgumentException; @SuppressWarnings("resource") public <T> T updateValue(T valueToUpdate, Object overrides) throws JsonMappingException; @Deprecated public com.fasterxml.jackson.databind.jsonschema.JsonSchema generateJsonSchema(Class<?> t) throws JsonMappingException; public void acceptJsonFormatVisitor(Class<?> type, JsonFormatVisitorWrapper visitor) throws JsonMappingException; public void acceptJsonFormatVisitor(JavaType type, JsonFormatVisitorWrapper visitor) throws JsonMappingException; protected DefaultSerializerProvider _serializerProvider(SerializationConfig config); protected final void _configAndWriteValue(JsonGenerator g, Object value) throws IOException; private final void _configAndWriteCloseable(JsonGenerator g, Object value, SerializationConfig cfg) throws IOException; private final void _writeCloseableValue(JsonGenerator g, Object value, SerializationConfig cfg) throws IOException; protected Object _readValue(DeserializationConfig cfg, JsonParser p, JavaType valueType) throws IOException; protected Object _readMapAndClose(JsonParser p0, JavaType valueType) throws IOException; protected JsonNode _readTreeAndClose(JsonParser p0) throws IOException; protected Object _unwrapAndDeserialize(JsonParser p, DeserializationContext ctxt, DeserializationConfig config, JavaType rootType, JsonDeserializer<Object> deser) throws IOException; protected DefaultDeserializationContext createDeserializationContext(JsonParser p, DeserializationConfig cfg); protected JsonToken _initForReading(JsonParser p, JavaType targetType) throws IOException; @Deprecated // since 2.9, use method that takes JavaType too protected JsonToken _initForReading(JsonParser p) throws IOException; protected final void _verifyNoTrailingTokens(JsonParser p, DeserializationContext ctxt, JavaType bindType) throws IOException; protected JsonDeserializer<Object> _findRootDeserializer(DeserializationContext ctxt, JavaType valueType) throws JsonMappingException; protected void _verifySchemaType(FormatSchema schema); public DefaultTypeResolverBuilder(DefaultTyping t); @Override public TypeDeserializer buildTypeDeserializer(DeserializationConfig config, JavaType baseType, Collection<NamedType> subtypes); @Override public TypeSerializer buildTypeSerializer(SerializationConfig config, JavaType baseType, Collection<NamedType> subtypes); public boolean useForType(JavaType t); @Override public Version getMapperVersion(); @SuppressWarnings("unchecked") @Override public <C extends ObjectCodec> C getOwner(); @Override public TypeFactory getTypeFactory(); @Override public boolean isEnabled(MapperFeature f); @Override public boolean isEnabled(DeserializationFeature f); @Override public boolean isEnabled(SerializationFeature f); @Override public boolean isEnabled(JsonFactory.Feature f); @Override public boolean isEnabled(JsonParser.Feature f); @Override public boolean isEnabled(JsonGenerator.Feature f); @Override public MutableConfigOverride configOverride(Class<?> type); @Override public void addDeserializers(Deserializers d); @Override public void addKeyDeserializers(KeyDeserializers d); @Override public void addBeanDeserializerModifier(BeanDeserializerModifier modifier); @Override public void addSerializers(Serializers s); @Override public void addKeySerializers(Serializers s); @Override public void addBeanSerializerModifier(BeanSerializerModifier modifier); @Override public void addAbstractTypeResolver(AbstractTypeResolver resolver); @Override public void addTypeModifier(TypeModifier modifier); @Override public void addValueInstantiators(ValueInstantiators instantiators); @Override public void setClassIntrospector(ClassIntrospector ci); @Override public void insertAnnotationIntrospector(AnnotationIntrospector ai); @Override public void appendAnnotationIntrospector(AnnotationIntrospector ai); @Override public void registerSubtypes(Class<?>... subtypes); @Override public void registerSubtypes(NamedType... subtypes); @Override public void registerSubtypes(Collection<Class<?>> subtypes); @Override public void setMixInAnnotations(Class<?> target, Class<?> mixinSource); @Override public void addDeserializationProblemHandler(DeserializationProblemHandler handler); @Override public void setNamingStrategy(PropertyNamingStrategy naming); @Override public ServiceLoader<T> run();
214
testProps
```java throws IOException; protected JsonNode _readTreeAndClose(JsonParser p0) throws IOException; protected Object _unwrapAndDeserialize(JsonParser p, DeserializationContext ctxt, DeserializationConfig config, JavaType rootType, JsonDeserializer<Object> deser) throws IOException; protected DefaultDeserializationContext createDeserializationContext(JsonParser p, DeserializationConfig cfg); protected JsonToken _initForReading(JsonParser p, JavaType targetType) throws IOException; @Deprecated // since 2.9, use method that takes JavaType too protected JsonToken _initForReading(JsonParser p) throws IOException; protected final void _verifyNoTrailingTokens(JsonParser p, DeserializationContext ctxt, JavaType bindType) throws IOException; protected JsonDeserializer<Object> _findRootDeserializer(DeserializationContext ctxt, JavaType valueType) throws JsonMappingException; protected void _verifySchemaType(FormatSchema schema); public DefaultTypeResolverBuilder(DefaultTyping t); @Override public TypeDeserializer buildTypeDeserializer(DeserializationConfig config, JavaType baseType, Collection<NamedType> subtypes); @Override public TypeSerializer buildTypeSerializer(SerializationConfig config, JavaType baseType, Collection<NamedType> subtypes); public boolean useForType(JavaType t); @Override public Version getMapperVersion(); @SuppressWarnings("unchecked") @Override public <C extends ObjectCodec> C getOwner(); @Override public TypeFactory getTypeFactory(); @Override public boolean isEnabled(MapperFeature f); @Override public boolean isEnabled(DeserializationFeature f); @Override public boolean isEnabled(SerializationFeature f); @Override public boolean isEnabled(JsonFactory.Feature f); @Override public boolean isEnabled(JsonParser.Feature f); @Override public boolean isEnabled(JsonGenerator.Feature f); @Override public MutableConfigOverride configOverride(Class<?> type); @Override public void addDeserializers(Deserializers d); @Override public void addKeyDeserializers(KeyDeserializers d); @Override public void addBeanDeserializerModifier(BeanDeserializerModifier modifier); @Override public void addSerializers(Serializers s); @Override public void addKeySerializers(Serializers s); @Override public void addBeanSerializerModifier(BeanSerializerModifier modifier); @Override public void addAbstractTypeResolver(AbstractTypeResolver resolver); @Override public void addTypeModifier(TypeModifier modifier); @Override public void addValueInstantiators(ValueInstantiators instantiators); @Override public void setClassIntrospector(ClassIntrospector ci); @Override public void insertAnnotationIntrospector(AnnotationIntrospector ai); @Override public void appendAnnotationIntrospector(AnnotationIntrospector ai); @Override public void registerSubtypes(Class<?>... subtypes); @Override public void registerSubtypes(NamedType... subtypes); @Override public void registerSubtypes(Collection<Class<?>> subtypes); @Override public void setMixInAnnotations(Class<?> target, Class<?> mixinSource); @Override public void addDeserializationProblemHandler(DeserializationProblemHandler handler); @Override public void setNamingStrategy(PropertyNamingStrategy naming); @Override public ServiceLoader<T> run(); } // Abstract Java Test Class package com.fasterxml.jackson.databind; import java.io.*; import java.util.*; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.util.MinimalPrettyPrinter; import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; import com.fasterxml.jackson.databind.introspect.VisibilityChecker; import com.fasterxml.jackson.databind.node.*; public class ObjectMapperTest extends BaseMapTest { final ObjectMapper MAPPER = new ObjectMapper(); public void testFactorFeatures(); public void testGeneratorFeatures(); public void testParserFeatures(); public void testCopy() throws Exception; public void testCopyOfConfigOverrides() throws Exception; public void testFailedCopy() throws Exception; public void testAnnotationIntrospectorCopyin(); public void testProps(); public void testConfigForPropertySorting() throws Exception; public void testJsonFactoryLinkage(); public void testProviderConfig() throws Exception; public void testCustomDefaultPrettyPrinter() throws Exception; public void testNonSerializabilityOfObject(); public void testEmptyBeanSerializability(); public void testSerializerProviderAccess() throws Exception; public void testCopyOfParserFeatures() throws Exception; public void testDataOutputViaMapper() throws Exception; @SuppressWarnings("unchecked") public void testDataInputViaMapper() throws Exception; public void setX(int v); protected Bean(); public Bean(int v); public FooPrettyPrinter(); @Override public void writeArrayValueSeparator(JsonGenerator g) throws IOException; } ``` You are a professional Java test case writer, please create a test case named `testProps` for the `ObjectMapper` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Test methods, other /********************************************************** */
205
// throws IOException; // protected JsonNode _readTreeAndClose(JsonParser p0) throws IOException; // protected Object _unwrapAndDeserialize(JsonParser p, DeserializationContext ctxt, // DeserializationConfig config, // JavaType rootType, JsonDeserializer<Object> deser) // throws IOException; // protected DefaultDeserializationContext createDeserializationContext(JsonParser p, // DeserializationConfig cfg); // protected JsonToken _initForReading(JsonParser p, JavaType targetType) throws IOException; // @Deprecated // since 2.9, use method that takes JavaType too // protected JsonToken _initForReading(JsonParser p) throws IOException; // protected final void _verifyNoTrailingTokens(JsonParser p, DeserializationContext ctxt, // JavaType bindType) // throws IOException; // protected JsonDeserializer<Object> _findRootDeserializer(DeserializationContext ctxt, // JavaType valueType) // throws JsonMappingException; // protected void _verifySchemaType(FormatSchema schema); // public DefaultTypeResolverBuilder(DefaultTyping t); // @Override // public TypeDeserializer buildTypeDeserializer(DeserializationConfig config, // JavaType baseType, Collection<NamedType> subtypes); // @Override // public TypeSerializer buildTypeSerializer(SerializationConfig config, // JavaType baseType, Collection<NamedType> subtypes); // public boolean useForType(JavaType t); // @Override // public Version getMapperVersion(); // @SuppressWarnings("unchecked") // @Override // public <C extends ObjectCodec> C getOwner(); // @Override // public TypeFactory getTypeFactory(); // @Override // public boolean isEnabled(MapperFeature f); // @Override // public boolean isEnabled(DeserializationFeature f); // @Override // public boolean isEnabled(SerializationFeature f); // @Override // public boolean isEnabled(JsonFactory.Feature f); // @Override // public boolean isEnabled(JsonParser.Feature f); // @Override // public boolean isEnabled(JsonGenerator.Feature f); // @Override // public MutableConfigOverride configOverride(Class<?> type); // @Override // public void addDeserializers(Deserializers d); // @Override // public void addKeyDeserializers(KeyDeserializers d); // @Override // public void addBeanDeserializerModifier(BeanDeserializerModifier modifier); // @Override // public void addSerializers(Serializers s); // @Override // public void addKeySerializers(Serializers s); // @Override // public void addBeanSerializerModifier(BeanSerializerModifier modifier); // @Override // public void addAbstractTypeResolver(AbstractTypeResolver resolver); // @Override // public void addTypeModifier(TypeModifier modifier); // @Override // public void addValueInstantiators(ValueInstantiators instantiators); // @Override // public void setClassIntrospector(ClassIntrospector ci); // @Override // public void insertAnnotationIntrospector(AnnotationIntrospector ai); // @Override // public void appendAnnotationIntrospector(AnnotationIntrospector ai); // @Override // public void registerSubtypes(Class<?>... subtypes); // @Override // public void registerSubtypes(NamedType... subtypes); // @Override // public void registerSubtypes(Collection<Class<?>> subtypes); // @Override // public void setMixInAnnotations(Class<?> target, Class<?> mixinSource); // @Override // public void addDeserializationProblemHandler(DeserializationProblemHandler handler); // @Override // public void setNamingStrategy(PropertyNamingStrategy naming); // @Override // public ServiceLoader<T> run(); // } // // // Abstract Java Test Class // package com.fasterxml.jackson.databind; // // import java.io.*; // import java.util.*; // import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; // import com.fasterxml.jackson.annotation.JsonInclude; // import com.fasterxml.jackson.annotation.JsonSetter; // import com.fasterxml.jackson.annotation.Nulls; // import com.fasterxml.jackson.core.*; // import com.fasterxml.jackson.core.util.MinimalPrettyPrinter; // import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; // import com.fasterxml.jackson.databind.introspect.VisibilityChecker; // import com.fasterxml.jackson.databind.node.*; // // // // public class ObjectMapperTest extends BaseMapTest // { // final ObjectMapper MAPPER = new ObjectMapper(); // // public void testFactorFeatures(); // public void testGeneratorFeatures(); // public void testParserFeatures(); // public void testCopy() throws Exception; // public void testCopyOfConfigOverrides() throws Exception; // public void testFailedCopy() throws Exception; // public void testAnnotationIntrospectorCopyin(); // public void testProps(); // public void testConfigForPropertySorting() throws Exception; // public void testJsonFactoryLinkage(); // public void testProviderConfig() throws Exception; // public void testCustomDefaultPrettyPrinter() throws Exception; // public void testNonSerializabilityOfObject(); // public void testEmptyBeanSerializability(); // public void testSerializerProviderAccess() throws Exception; // public void testCopyOfParserFeatures() throws Exception; // public void testDataOutputViaMapper() throws Exception; // @SuppressWarnings("unchecked") // public void testDataInputViaMapper() throws Exception; // public void setX(int v); // protected Bean(); // public Bean(int v); // public FooPrettyPrinter(); // @Override // public void writeArrayValueSeparator(JsonGenerator g) throws IOException; // } // You are a professional Java test case writer, please create a test case named `testProps` for the `ObjectMapper` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Test methods, other /********************************************************** */ public void testProps() {
/* /********************************************************** /* Test methods, other /********************************************************** */
112
com.fasterxml.jackson.databind.ObjectMapper
src/test/java
```java throws IOException; protected JsonNode _readTreeAndClose(JsonParser p0) throws IOException; protected Object _unwrapAndDeserialize(JsonParser p, DeserializationContext ctxt, DeserializationConfig config, JavaType rootType, JsonDeserializer<Object> deser) throws IOException; protected DefaultDeserializationContext createDeserializationContext(JsonParser p, DeserializationConfig cfg); protected JsonToken _initForReading(JsonParser p, JavaType targetType) throws IOException; @Deprecated // since 2.9, use method that takes JavaType too protected JsonToken _initForReading(JsonParser p) throws IOException; protected final void _verifyNoTrailingTokens(JsonParser p, DeserializationContext ctxt, JavaType bindType) throws IOException; protected JsonDeserializer<Object> _findRootDeserializer(DeserializationContext ctxt, JavaType valueType) throws JsonMappingException; protected void _verifySchemaType(FormatSchema schema); public DefaultTypeResolverBuilder(DefaultTyping t); @Override public TypeDeserializer buildTypeDeserializer(DeserializationConfig config, JavaType baseType, Collection<NamedType> subtypes); @Override public TypeSerializer buildTypeSerializer(SerializationConfig config, JavaType baseType, Collection<NamedType> subtypes); public boolean useForType(JavaType t); @Override public Version getMapperVersion(); @SuppressWarnings("unchecked") @Override public <C extends ObjectCodec> C getOwner(); @Override public TypeFactory getTypeFactory(); @Override public boolean isEnabled(MapperFeature f); @Override public boolean isEnabled(DeserializationFeature f); @Override public boolean isEnabled(SerializationFeature f); @Override public boolean isEnabled(JsonFactory.Feature f); @Override public boolean isEnabled(JsonParser.Feature f); @Override public boolean isEnabled(JsonGenerator.Feature f); @Override public MutableConfigOverride configOverride(Class<?> type); @Override public void addDeserializers(Deserializers d); @Override public void addKeyDeserializers(KeyDeserializers d); @Override public void addBeanDeserializerModifier(BeanDeserializerModifier modifier); @Override public void addSerializers(Serializers s); @Override public void addKeySerializers(Serializers s); @Override public void addBeanSerializerModifier(BeanSerializerModifier modifier); @Override public void addAbstractTypeResolver(AbstractTypeResolver resolver); @Override public void addTypeModifier(TypeModifier modifier); @Override public void addValueInstantiators(ValueInstantiators instantiators); @Override public void setClassIntrospector(ClassIntrospector ci); @Override public void insertAnnotationIntrospector(AnnotationIntrospector ai); @Override public void appendAnnotationIntrospector(AnnotationIntrospector ai); @Override public void registerSubtypes(Class<?>... subtypes); @Override public void registerSubtypes(NamedType... subtypes); @Override public void registerSubtypes(Collection<Class<?>> subtypes); @Override public void setMixInAnnotations(Class<?> target, Class<?> mixinSource); @Override public void addDeserializationProblemHandler(DeserializationProblemHandler handler); @Override public void setNamingStrategy(PropertyNamingStrategy naming); @Override public ServiceLoader<T> run(); } // Abstract Java Test Class package com.fasterxml.jackson.databind; import java.io.*; import java.util.*; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.util.MinimalPrettyPrinter; import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; import com.fasterxml.jackson.databind.introspect.VisibilityChecker; import com.fasterxml.jackson.databind.node.*; public class ObjectMapperTest extends BaseMapTest { final ObjectMapper MAPPER = new ObjectMapper(); public void testFactorFeatures(); public void testGeneratorFeatures(); public void testParserFeatures(); public void testCopy() throws Exception; public void testCopyOfConfigOverrides() throws Exception; public void testFailedCopy() throws Exception; public void testAnnotationIntrospectorCopyin(); public void testProps(); public void testConfigForPropertySorting() throws Exception; public void testJsonFactoryLinkage(); public void testProviderConfig() throws Exception; public void testCustomDefaultPrettyPrinter() throws Exception; public void testNonSerializabilityOfObject(); public void testEmptyBeanSerializability(); public void testSerializerProviderAccess() throws Exception; public void testCopyOfParserFeatures() throws Exception; public void testDataOutputViaMapper() throws Exception; @SuppressWarnings("unchecked") public void testDataInputViaMapper() throws Exception; public void setX(int v); protected Bean(); public Bean(int v); public FooPrettyPrinter(); @Override public void writeArrayValueSeparator(JsonGenerator g) throws IOException; } ``` You are a professional Java test case writer, please create a test case named `testProps` for the `ObjectMapper` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Test methods, other /********************************************************** */ public void testProps() { ```
public class ObjectMapper extends ObjectCodec implements Versioned, java.io.Serializable // as of 2.1
package com.fasterxml.jackson.databind; import java.io.*; import java.util.*; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.util.MinimalPrettyPrinter; import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; import com.fasterxml.jackson.databind.introspect.VisibilityChecker; import com.fasterxml.jackson.databind.node.*;
public void testFactorFeatures(); public void testGeneratorFeatures(); public void testParserFeatures(); public void testCopy() throws Exception; public void testCopyOfConfigOverrides() throws Exception; public void testFailedCopy() throws Exception; public void testAnnotationIntrospectorCopyin(); public void testProps(); public void testConfigForPropertySorting() throws Exception; public void testJsonFactoryLinkage(); public void testProviderConfig() throws Exception; public void testCustomDefaultPrettyPrinter() throws Exception; public void testNonSerializabilityOfObject(); public void testEmptyBeanSerializability(); public void testSerializerProviderAccess() throws Exception; public void testCopyOfParserFeatures() throws Exception; public void testDataOutputViaMapper() throws Exception; @SuppressWarnings("unchecked") public void testDataInputViaMapper() throws Exception; public void setX(int v); protected Bean(); public Bean(int v); public FooPrettyPrinter(); @Override public void writeArrayValueSeparator(JsonGenerator g) throws IOException;
1966ffe18b03fc647d571dbfb1adc1a18385a5d567bf4f449e107993d8879e08
[ "com.fasterxml.jackson.databind.ObjectMapperTest::testProps" ]
private static final long serialVersionUID = 2L; private final static JavaType JSON_NODE_TYPE = SimpleType.constructUnsafe(JsonNode.class); protected final static AnnotationIntrospector DEFAULT_ANNOTATION_INTROSPECTOR = new JacksonAnnotationIntrospector(); protected final static BaseSettings DEFAULT_BASE = new BaseSettings( null, // cannot share global ClassIntrospector any more (2.5+) DEFAULT_ANNOTATION_INTROSPECTOR, null, TypeFactory.defaultInstance(), null, StdDateFormat.instance, null, Locale.getDefault(), null, // to indicate "use Jackson default TimeZone" (UTC since Jackson 2.7) Base64Variants.getDefaultVariant() // 2.1 ); protected final JsonFactory _jsonFactory; protected TypeFactory _typeFactory; protected InjectableValues _injectableValues; protected SubtypeResolver _subtypeResolver; protected final ConfigOverrides _configOverrides; protected SimpleMixInResolver _mixIns; protected SerializationConfig _serializationConfig; protected DefaultSerializerProvider _serializerProvider; protected SerializerFactory _serializerFactory; protected DeserializationConfig _deserializationConfig; protected DefaultDeserializationContext _deserializationContext; protected Set<Object> _registeredModuleTypes; final protected ConcurrentHashMap<JavaType, JsonDeserializer<Object>> _rootDeserializers = new ConcurrentHashMap<JavaType, JsonDeserializer<Object>>(64, 0.6f, 2);
public void testProps()
final ObjectMapper MAPPER = new ObjectMapper();
JacksonDatabind
package com.fasterxml.jackson.databind; import java.io.*; import java.util.*; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; import com.fasterxml.jackson.annotation.Nulls; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.util.MinimalPrettyPrinter; import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; import com.fasterxml.jackson.databind.introspect.VisibilityChecker; import com.fasterxml.jackson.databind.node.*; public class ObjectMapperTest extends BaseMapTest { static class Bean { int value = 3; public void setX(int v) { value = v; } protected Bean() { } public Bean(int v) { value = v; } } static class EmptyBean { } @SuppressWarnings("serial") static class MyAnnotationIntrospector extends JacksonAnnotationIntrospector { } // for [databind#689] @SuppressWarnings("serial") static class FooPrettyPrinter extends MinimalPrettyPrinter { public FooPrettyPrinter() { super(" /*foo*/ "); } @Override public void writeArrayValueSeparator(JsonGenerator g) throws IOException { g.writeRaw(" , "); } } // for [databind#206] @SuppressWarnings("serial") static class NoCopyMapper extends ObjectMapper { } final ObjectMapper MAPPER = new ObjectMapper(); /* /********************************************************** /* Test methods, config /********************************************************** */ public void testFactorFeatures() { assertTrue(MAPPER.isEnabled(JsonFactory.Feature.CANONICALIZE_FIELD_NAMES)); } public void testGeneratorFeatures() { // and also for mapper ObjectMapper mapper = new ObjectMapper(); assertFalse(mapper.isEnabled(JsonGenerator.Feature.ESCAPE_NON_ASCII)); assertTrue(mapper.isEnabled(JsonGenerator.Feature.QUOTE_FIELD_NAMES)); mapper.disable(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM, JsonGenerator.Feature.QUOTE_FIELD_NAMES); } public void testParserFeatures() { // and also for mapper ObjectMapper mapper = new ObjectMapper(); assertTrue(mapper.isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)); assertFalse(mapper.isEnabled(JsonParser.Feature.ALLOW_COMMENTS)); mapper.disable(JsonParser.Feature.AUTO_CLOSE_SOURCE, JsonParser.Feature.STRICT_DUPLICATE_DETECTION); assertFalse(mapper.isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)); } /* /********************************************************** /* Test methods, mapper.copy() /********************************************************** */ // [databind#28]: ObjectMapper.copy() public void testCopy() throws Exception { ObjectMapper m = new ObjectMapper(); assertTrue(m.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); m.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); assertFalse(m.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); InjectableValues inj = new InjectableValues.Std(); m.setInjectableValues(inj); assertFalse(m.isEnabled(JsonParser.Feature.ALLOW_COMMENTS)); m.enable(JsonParser.Feature.ALLOW_COMMENTS); assertTrue(m.isEnabled(JsonParser.Feature.ALLOW_COMMENTS)); // // First: verify that handling of features is decoupled: ObjectMapper m2 = m.copy(); assertFalse(m2.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); m2.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); assertTrue(m2.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); assertSame(inj, m2.getInjectableValues()); // but should NOT change the original assertFalse(m.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); // nor vice versa: assertFalse(m.isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE)); assertFalse(m2.isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE)); m.enable(DeserializationFeature.UNWRAP_ROOT_VALUE); assertTrue(m.isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE)); assertFalse(m2.isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE)); // // Also, underlying JsonFactory instances should be distinct assertNotSame(m.getFactory(), m2.getFactory()); // [databind#122]: Need to ensure mix-ins are not shared assertEquals(0, m.getSerializationConfig().mixInCount()); assertEquals(0, m2.getSerializationConfig().mixInCount()); assertEquals(0, m.getDeserializationConfig().mixInCount()); assertEquals(0, m2.getDeserializationConfig().mixInCount()); m.addMixIn(String.class, Integer.class); assertEquals(1, m.getSerializationConfig().mixInCount()); assertEquals(0, m2.getSerializationConfig().mixInCount()); assertEquals(1, m.getDeserializationConfig().mixInCount()); assertEquals(0, m2.getDeserializationConfig().mixInCount()); // [databind#913]: Ensure JsonFactory Features copied assertTrue(m2.isEnabled(JsonParser.Feature.ALLOW_COMMENTS)); } // [databind#1580] public void testCopyOfConfigOverrides() throws Exception { ObjectMapper m = new ObjectMapper(); SerializationConfig config = m.getSerializationConfig(); assertEquals(JsonInclude.Value.empty(), config.getDefaultPropertyInclusion()); assertEquals(JsonSetter.Value.empty(), config.getDefaultSetterInfo()); assertNull(config.getDefaultMergeable()); VisibilityChecker<?> defaultVis = config.getDefaultVisibilityChecker(); assertEquals(VisibilityChecker.Std.class, defaultVis.getClass()); // change JsonInclude.Value customIncl = JsonInclude.Value.empty().withValueInclusion(JsonInclude.Include.NON_DEFAULT); m.setDefaultPropertyInclusion(customIncl); JsonSetter.Value customSetter = JsonSetter.Value.forValueNulls(Nulls.SKIP); m.setDefaultSetterInfo(customSetter); m.setDefaultMergeable(Boolean.TRUE); VisibilityChecker<?> customVis = VisibilityChecker.Std.defaultInstance() .withFieldVisibility(Visibility.ANY); m.setVisibility(customVis); assertSame(customVis, m.getVisibilityChecker()); // and verify that copy retains these settings ObjectMapper m2 = m.copy(); SerializationConfig config2 = m2.getSerializationConfig(); assertSame(customIncl, config2.getDefaultPropertyInclusion()); assertSame(customSetter, config2.getDefaultSetterInfo()); assertEquals(Boolean.TRUE, config2.getDefaultMergeable()); assertSame(customVis, config2.getDefaultVisibilityChecker()); } public void testFailedCopy() throws Exception { NoCopyMapper src = new NoCopyMapper(); try { src.copy(); fail("Should not pass"); } catch (IllegalStateException e) { verifyException(e, "does not override copy()"); } } public void testAnnotationIntrospectorCopyin() { ObjectMapper m = new ObjectMapper(); m.setAnnotationIntrospector(new MyAnnotationIntrospector()); assertEquals(MyAnnotationIntrospector.class, m.getDeserializationConfig().getAnnotationIntrospector().getClass()); ObjectMapper m2 = m.copy(); assertEquals(MyAnnotationIntrospector.class, m2.getDeserializationConfig().getAnnotationIntrospector().getClass()); assertEquals(MyAnnotationIntrospector.class, m2.getSerializationConfig().getAnnotationIntrospector().getClass()); } /* /********************************************************** /* Test methods, other /********************************************************** */ public void testProps() { ObjectMapper m = new ObjectMapper(); // should have default factory assertNotNull(m.getNodeFactory()); JsonNodeFactory nf = new JsonNodeFactory(true); m.setNodeFactory(nf); assertNull(m.getInjectableValues()); assertSame(nf, m.getNodeFactory()); } // Test to ensure that we can check property ordering defaults... public void testConfigForPropertySorting() throws Exception { ObjectMapper m = new ObjectMapper(); // sort-alphabetically is disabled by default: assertFalse(m.isEnabled(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY)); SerializationConfig sc = m.getSerializationConfig(); assertFalse(sc.isEnabled(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY)); assertFalse(sc.shouldSortPropertiesAlphabetically()); DeserializationConfig dc = m.getDeserializationConfig(); assertFalse(dc.shouldSortPropertiesAlphabetically()); // but when enabled, should be visible: m.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY); sc = m.getSerializationConfig(); assertTrue(sc.isEnabled(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY)); assertTrue(sc.shouldSortPropertiesAlphabetically()); dc = m.getDeserializationConfig(); // and not just via SerializationConfig, but also via DeserializationConfig assertTrue(dc.isEnabled(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY)); assertTrue(dc.shouldSortPropertiesAlphabetically()); } public void testJsonFactoryLinkage() { // first, implicit factory, giving implicit linkage assertSame(MAPPER, MAPPER.getFactory().getCodec()); // and then explicit factory, which should also be implicitly linked JsonFactory f = new JsonFactory(); ObjectMapper m = new ObjectMapper(f); assertSame(f, m.getFactory()); assertSame(m, f.getCodec()); } public void testProviderConfig() throws Exception { ObjectMapper m = new ObjectMapper(); final String JSON = "{ \"x\" : 3 }"; assertEquals(0, m._deserializationContext._cache.cachedDeserializersCount()); // and then should get one constructed for: Bean bean = m.readValue(JSON, Bean.class); assertNotNull(bean); // Since 2.6, serializer for int also cached: assertEquals(2, m._deserializationContext._cache.cachedDeserializersCount()); m._deserializationContext._cache.flushCachedDeserializers(); assertEquals(0, m._deserializationContext._cache.cachedDeserializersCount()); // 07-Nov-2014, tatu: As per [databind#604] verify that Maps also get cached m = new ObjectMapper(); List<?> stuff = m.readValue("[ ]", List.class); assertNotNull(stuff); // may look odd, but due to "Untyped" deserializer thing, we actually have // 4 deserializers (int, List<?>, Map<?,?>, Object) assertEquals(4, m._deserializationContext._cache.cachedDeserializersCount()); } // For [databind#689] public void testCustomDefaultPrettyPrinter() throws Exception { final ObjectMapper m = new ObjectMapper(); final int[] input = new int[] { 1, 2 }; // without anything else, compact: assertEquals("[1,2]", m.writeValueAsString(input)); // or with default, get... defaults: m.enable(SerializationFeature.INDENT_OUTPUT); assertEquals("[ 1, 2 ]", m.writeValueAsString(input)); assertEquals("[ 1, 2 ]", m.writerWithDefaultPrettyPrinter().writeValueAsString(input)); assertEquals("[ 1, 2 ]", m.writer().withDefaultPrettyPrinter().writeValueAsString(input)); // but then with our custom thingy... m.setDefaultPrettyPrinter(new FooPrettyPrinter()); assertEquals("[1 , 2]", m.writeValueAsString(input)); assertEquals("[1 , 2]", m.writerWithDefaultPrettyPrinter().writeValueAsString(input)); assertEquals("[1 , 2]", m.writer().withDefaultPrettyPrinter().writeValueAsString(input)); // and yet, can disable too assertEquals("[1,2]", m.writer().without(SerializationFeature.INDENT_OUTPUT) .writeValueAsString(input)); } // For [databind#703], [databind#978] public void testNonSerializabilityOfObject() { ObjectMapper m = new ObjectMapper(); assertFalse(m.canSerialize(Object.class)); // but this used to pass, incorrectly, second time around assertFalse(m.canSerialize(Object.class)); // [databind#978]: Different answer if empty Beans ARE allowed m = new ObjectMapper(); m.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); assertTrue(m.canSerialize(Object.class)); assertTrue(MAPPER.writer().without(SerializationFeature.FAIL_ON_EMPTY_BEANS) .canSerialize(Object.class)); assertFalse(MAPPER.writer().with(SerializationFeature.FAIL_ON_EMPTY_BEANS) .canSerialize(Object.class)); } // for [databind#756] public void testEmptyBeanSerializability() { // with default settings, error assertFalse(MAPPER.writer().with(SerializationFeature.FAIL_ON_EMPTY_BEANS) .canSerialize(EmptyBean.class)); // but with changes assertTrue(MAPPER.writer().without(SerializationFeature.FAIL_ON_EMPTY_BEANS) .canSerialize(EmptyBean.class)); } // for [databind#898] public void testSerializerProviderAccess() throws Exception { // ensure we have "fresh" instance, just in case ObjectMapper mapper = new ObjectMapper(); JsonSerializer<?> ser = mapper.getSerializerProviderInstance() .findValueSerializer(Bean.class); assertNotNull(ser); assertEquals(Bean.class, ser.handledType()); } // for [databind#1074] public void testCopyOfParserFeatures() throws Exception { // ensure we have "fresh" instance to start with ObjectMapper mapper = new ObjectMapper(); assertFalse(mapper.isEnabled(JsonParser.Feature.ALLOW_COMMENTS)); mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); assertTrue(mapper.isEnabled(JsonParser.Feature.ALLOW_COMMENTS)); ObjectMapper copy = mapper.copy(); assertTrue(copy.isEnabled(JsonParser.Feature.ALLOW_COMMENTS)); // also verify there's no back-linkage copy.configure(JsonParser.Feature.ALLOW_COMMENTS, false); assertFalse(copy.isEnabled(JsonParser.Feature.ALLOW_COMMENTS)); assertTrue(mapper.isEnabled(JsonParser.Feature.ALLOW_COMMENTS)); } // since 2.8 public void testDataOutputViaMapper() throws Exception { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ObjectNode input = MAPPER.createObjectNode(); input.put("a", 1); DataOutput data = new DataOutputStream(bytes); final String exp = "{\"a\":1}"; MAPPER.writeValue(data, input); assertEquals(exp, bytes.toString("UTF-8")); // and also via ObjectWriter... bytes.reset(); data = new DataOutputStream(bytes); MAPPER.writer().writeValue(data, input); assertEquals(exp, bytes.toString("UTF-8")); } // since 2.8 @SuppressWarnings("unchecked") public void testDataInputViaMapper() throws Exception { byte[] src = "{\"a\":1}".getBytes("UTF-8"); DataInput input = new DataInputStream(new ByteArrayInputStream(src)); Map<String,Object> map = (Map<String,Object>) MAPPER.readValue(input, Map.class); assertEquals(Integer.valueOf(1), map.get("a")); input = new DataInputStream(new ByteArrayInputStream(src)); // and via ObjectReader map = MAPPER.readerFor(Map.class) .readValue(input); assertEquals(Integer.valueOf(1), map.get("a")); input = new DataInputStream(new ByteArrayInputStream(src)); JsonNode n = MAPPER.readerFor(Map.class) .readTree(input); assertNotNull(n); } }
[ { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectMapper.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectMapper", "be_test_function_name": "defaultClassIntrospector", "be_test_function_signature": "()Lcom/fasterxml/jackson/databind/introspect/ClassIntrospector;", "line_numbers": [ "591" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectMapper.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectMapper", "be_test_function_name": "getInjectableValues", "be_test_function_signature": "()Lcom/fasterxml/jackson/databind/InjectableValues;", "line_numbers": [ "1907" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectMapper.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectMapper", "be_test_function_name": "getNodeFactory", "be_test_function_signature": "()Lcom/fasterxml/jackson/databind/node/JsonNodeFactory;", "line_numbers": [ "1707" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectMapper.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectMapper", "be_test_function_name": "setNodeFactory", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/node/JsonNodeFactory;)Lcom/fasterxml/jackson/databind/ObjectMapper;", "line_numbers": [ "1716", "1717" ], "method_line_rate": 1 } ]
public class StringEscapeUtilsTest
@Test public void testEscapeHtmlHighUnicode() throws java.io.UnsupportedEncodingException { // this is the utf8 representation of the character: // COUNTING ROD UNIT DIGIT THREE // in Unicode // codepoint: U+1D362 final byte[] data = new byte[] { (byte)0xF0, (byte)0x9D, (byte)0x8D, (byte)0xA2 }; final String original = new String(data, "UTF8"); final String escaped = StringEscapeUtils.escapeHtml4( original ); assertEquals( "High Unicode should not have been escaped", original, escaped); final String unescaped = StringEscapeUtils.unescapeHtml4( escaped ); assertEquals( "High Unicode should have been unchanged", original, unescaped); // TODO: I think this should hold, needs further investigation // String unescapedFromEntity = StringEscapeUtils.unescapeHtml4( "&#119650;" ); // assertEquals( "High Unicode should have been unescaped", original, unescapedFromEntity); }
// public static final CharSequenceTranslator UNESCAPE_HTML3 = // new AggregateTranslator( // new LookupTranslator(EntityArrays.BASIC_UNESCAPE()), // new LookupTranslator(EntityArrays.ISO8859_1_UNESCAPE()), // new NumericEntityUnescaper() // ); // public static final CharSequenceTranslator UNESCAPE_HTML4 = // new AggregateTranslator( // new LookupTranslator(EntityArrays.BASIC_UNESCAPE()), // new LookupTranslator(EntityArrays.ISO8859_1_UNESCAPE()), // new LookupTranslator(EntityArrays.HTML40_EXTENDED_UNESCAPE()), // new NumericEntityUnescaper() // ); // public static final CharSequenceTranslator UNESCAPE_XML = // new AggregateTranslator( // new LookupTranslator(EntityArrays.BASIC_UNESCAPE()), // new LookupTranslator(EntityArrays.APOS_UNESCAPE()), // new NumericEntityUnescaper() // ); // public static final CharSequenceTranslator UNESCAPE_CSV = new CsvUnescaper(); // // public StringEscapeUtils(); // public static final String escapeJava(final String input); // public static final String escapeEcmaScript(final String input); // public static final String escapeJson(final String input); // public static final String unescapeJava(final String input); // public static final String unescapeEcmaScript(final String input); // public static final String unescapeJson(final String input); // public static final String escapeHtml4(final String input); // public static final String escapeHtml3(final String input); // public static final String unescapeHtml4(final String input); // public static final String unescapeHtml3(final String input); // public static final String escapeXml(final String input); // public static final String unescapeXml(final String input); // public static final String escapeCsv(final String input); // public static final String unescapeCsv(final String input); // @Override // public int translate(final CharSequence input, final int index, final Writer out) throws IOException; // @Override // public int translate(final CharSequence input, final int index, final Writer out) throws IOException; // } // // // Abstract Java Test Class // package org.apache.commons.lang3; // // import static org.junit.Assert.assertEquals; // import static org.junit.Assert.assertFalse; // import static org.junit.Assert.assertNotNull; // import static org.junit.Assert.assertTrue; // import static org.junit.Assert.fail; // import java.io.FileInputStream; // import java.io.IOException; // import java.io.StringWriter; // import java.lang.reflect.Constructor; // import java.lang.reflect.Modifier; // import org.apache.commons.io.IOUtils; // import org.apache.commons.lang3.text.translate.CharSequenceTranslator; // import org.apache.commons.lang3.text.translate.NumericEntityEscaper; // import org.junit.Test; // // // // public class StringEscapeUtilsTest { // private final static String FOO = "foo"; // private static final String[][] HTML_ESCAPES = { // {"no escaping", "plain text", "plain text"}, // {"no escaping", "plain text", "plain text"}, // {"empty string", "", ""}, // {"null", null, null}, // {"ampersand", "bread &amp; butter", "bread & butter"}, // {"quotes", "&quot;bread&quot; &amp; butter", "\"bread\" & butter"}, // {"final character only", "greater than &gt;", "greater than >"}, // {"first character only", "&lt; less than", "< less than"}, // {"apostrophe", "Huntington's chorea", "Huntington's chorea"}, // {"languages", "English,Fran&ccedil;ais,\u65E5\u672C\u8A9E (nihongo)", "English,Fran\u00E7ais,\u65E5\u672C\u8A9E (nihongo)"}, // {"8-bit ascii shouldn't number-escape", "\u0080\u009F", "\u0080\u009F"}, // }; // // @Test // public void testConstructor(); // @Test // public void testEscapeJava() throws IOException; // @Test // public void testEscapeJavaWithSlash(); // private void assertEscapeJava(final String escaped, final String original) throws IOException; // private void assertEscapeJava(String message, final String expected, final String original) throws IOException; // @Test // public void testUnescapeJava() throws IOException; // private void assertUnescapeJava(final String unescaped, final String original) throws IOException; // private void assertUnescapeJava(final String message, final String unescaped, final String original) throws IOException; // @Test // public void testEscapeEcmaScript(); // @Test // public void testEscapeHtml(); // @Test // public void testUnescapeHtml4(); // @Test // public void testUnescapeHexCharsHtml(); // @Test // public void testUnescapeUnknownEntity() throws Exception; // @Test // public void testEscapeHtmlVersions() throws Exception; // @Test // public void testEscapeXml() throws Exception; // @Test // public void testEscapeXmlSupplementaryCharacters(); // @Test // public void testEscapeXmlAllCharacters(); // @Test // public void testUnescapeXmlSupplementaryCharacters(); // @Test // public void testStandaloneAmphersand(); // @Test // public void testLang313(); // @Test // public void testEscapeCsvString() throws Exception; // @Test // public void testEscapeCsvWriter() throws Exception; // private void checkCsvEscapeWriter(final String expected, final String value); // @Test // public void testUnescapeCsvString() throws Exception; // @Test // public void testUnescapeCsvWriter() throws Exception; // private void checkCsvUnescapeWriter(final String expected, final String value); // @Test // public void testEscapeHtmlHighUnicode() throws java.io.UnsupportedEncodingException; // @Test // public void testEscapeHiragana(); // @Test // public void testLang708() throws IOException; // @Test // public void testLang720(); // @Test // public void testEscapeJson(); // } // You are a professional Java test case writer, please create a test case named `testEscapeHtmlHighUnicode` for the `StringEscapeUtils` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests // https://issues.apache.org/jira/browse/LANG-480 * * @throws java.io.UnsupportedEncodingException */
src/test/java/org/apache/commons/lang3/StringEscapeUtilsTest.java
package org.apache.commons.lang3; import java.io.IOException; import java.io.Writer; import org.apache.commons.lang3.text.translate.AggregateTranslator; import org.apache.commons.lang3.text.translate.CharSequenceTranslator; import org.apache.commons.lang3.text.translate.EntityArrays; import org.apache.commons.lang3.text.translate.JavaUnicodeEscaper; import org.apache.commons.lang3.text.translate.LookupTranslator; import org.apache.commons.lang3.text.translate.NumericEntityUnescaper; import org.apache.commons.lang3.text.translate.OctalUnescaper; import org.apache.commons.lang3.text.translate.UnicodeUnescaper;
public StringEscapeUtils(); public static final String escapeJava(final String input); public static final String escapeEcmaScript(final String input); public static final String escapeJson(final String input); public static final String unescapeJava(final String input); public static final String unescapeEcmaScript(final String input); public static final String unescapeJson(final String input); public static final String escapeHtml4(final String input); public static final String escapeHtml3(final String input); public static final String unescapeHtml4(final String input); public static final String unescapeHtml3(final String input); public static final String escapeXml(final String input); public static final String unescapeXml(final String input); public static final String escapeCsv(final String input); public static final String unescapeCsv(final String input); @Override public int translate(final CharSequence input, final int index, final Writer out) throws IOException; @Override public int translate(final CharSequence input, final int index, final Writer out) throws IOException;
488
testEscapeHtmlHighUnicode
```java public static final CharSequenceTranslator UNESCAPE_HTML3 = new AggregateTranslator( new LookupTranslator(EntityArrays.BASIC_UNESCAPE()), new LookupTranslator(EntityArrays.ISO8859_1_UNESCAPE()), new NumericEntityUnescaper() ); public static final CharSequenceTranslator UNESCAPE_HTML4 = new AggregateTranslator( new LookupTranslator(EntityArrays.BASIC_UNESCAPE()), new LookupTranslator(EntityArrays.ISO8859_1_UNESCAPE()), new LookupTranslator(EntityArrays.HTML40_EXTENDED_UNESCAPE()), new NumericEntityUnescaper() ); public static final CharSequenceTranslator UNESCAPE_XML = new AggregateTranslator( new LookupTranslator(EntityArrays.BASIC_UNESCAPE()), new LookupTranslator(EntityArrays.APOS_UNESCAPE()), new NumericEntityUnescaper() ); public static final CharSequenceTranslator UNESCAPE_CSV = new CsvUnescaper(); public StringEscapeUtils(); public static final String escapeJava(final String input); public static final String escapeEcmaScript(final String input); public static final String escapeJson(final String input); public static final String unescapeJava(final String input); public static final String unescapeEcmaScript(final String input); public static final String unescapeJson(final String input); public static final String escapeHtml4(final String input); public static final String escapeHtml3(final String input); public static final String unescapeHtml4(final String input); public static final String unescapeHtml3(final String input); public static final String escapeXml(final String input); public static final String unescapeXml(final String input); public static final String escapeCsv(final String input); public static final String unescapeCsv(final String input); @Override public int translate(final CharSequence input, final int index, final Writer out) throws IOException; @Override public int translate(final CharSequence input, final int index, final Writer out) throws IOException; } // Abstract Java Test Class package org.apache.commons.lang3; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.FileInputStream; import java.io.IOException; import java.io.StringWriter; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.text.translate.CharSequenceTranslator; import org.apache.commons.lang3.text.translate.NumericEntityEscaper; import org.junit.Test; public class StringEscapeUtilsTest { private final static String FOO = "foo"; private static final String[][] HTML_ESCAPES = { {"no escaping", "plain text", "plain text"}, {"no escaping", "plain text", "plain text"}, {"empty string", "", ""}, {"null", null, null}, {"ampersand", "bread &amp; butter", "bread & butter"}, {"quotes", "&quot;bread&quot; &amp; butter", "\"bread\" & butter"}, {"final character only", "greater than &gt;", "greater than >"}, {"first character only", "&lt; less than", "< less than"}, {"apostrophe", "Huntington's chorea", "Huntington's chorea"}, {"languages", "English,Fran&ccedil;ais,\u65E5\u672C\u8A9E (nihongo)", "English,Fran\u00E7ais,\u65E5\u672C\u8A9E (nihongo)"}, {"8-bit ascii shouldn't number-escape", "\u0080\u009F", "\u0080\u009F"}, }; @Test public void testConstructor(); @Test public void testEscapeJava() throws IOException; @Test public void testEscapeJavaWithSlash(); private void assertEscapeJava(final String escaped, final String original) throws IOException; private void assertEscapeJava(String message, final String expected, final String original) throws IOException; @Test public void testUnescapeJava() throws IOException; private void assertUnescapeJava(final String unescaped, final String original) throws IOException; private void assertUnescapeJava(final String message, final String unescaped, final String original) throws IOException; @Test public void testEscapeEcmaScript(); @Test public void testEscapeHtml(); @Test public void testUnescapeHtml4(); @Test public void testUnescapeHexCharsHtml(); @Test public void testUnescapeUnknownEntity() throws Exception; @Test public void testEscapeHtmlVersions() throws Exception; @Test public void testEscapeXml() throws Exception; @Test public void testEscapeXmlSupplementaryCharacters(); @Test public void testEscapeXmlAllCharacters(); @Test public void testUnescapeXmlSupplementaryCharacters(); @Test public void testStandaloneAmphersand(); @Test public void testLang313(); @Test public void testEscapeCsvString() throws Exception; @Test public void testEscapeCsvWriter() throws Exception; private void checkCsvEscapeWriter(final String expected, final String value); @Test public void testUnescapeCsvString() throws Exception; @Test public void testUnescapeCsvWriter() throws Exception; private void checkCsvUnescapeWriter(final String expected, final String value); @Test public void testEscapeHtmlHighUnicode() throws java.io.UnsupportedEncodingException; @Test public void testEscapeHiragana(); @Test public void testLang708() throws IOException; @Test public void testLang720(); @Test public void testEscapeJson(); } ``` You are a professional Java test case writer, please create a test case named `testEscapeHtmlHighUnicode` for the `StringEscapeUtils` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests // https://issues.apache.org/jira/browse/LANG-480 * * @throws java.io.UnsupportedEncodingException */
469
// public static final CharSequenceTranslator UNESCAPE_HTML3 = // new AggregateTranslator( // new LookupTranslator(EntityArrays.BASIC_UNESCAPE()), // new LookupTranslator(EntityArrays.ISO8859_1_UNESCAPE()), // new NumericEntityUnescaper() // ); // public static final CharSequenceTranslator UNESCAPE_HTML4 = // new AggregateTranslator( // new LookupTranslator(EntityArrays.BASIC_UNESCAPE()), // new LookupTranslator(EntityArrays.ISO8859_1_UNESCAPE()), // new LookupTranslator(EntityArrays.HTML40_EXTENDED_UNESCAPE()), // new NumericEntityUnescaper() // ); // public static final CharSequenceTranslator UNESCAPE_XML = // new AggregateTranslator( // new LookupTranslator(EntityArrays.BASIC_UNESCAPE()), // new LookupTranslator(EntityArrays.APOS_UNESCAPE()), // new NumericEntityUnescaper() // ); // public static final CharSequenceTranslator UNESCAPE_CSV = new CsvUnescaper(); // // public StringEscapeUtils(); // public static final String escapeJava(final String input); // public static final String escapeEcmaScript(final String input); // public static final String escapeJson(final String input); // public static final String unescapeJava(final String input); // public static final String unescapeEcmaScript(final String input); // public static final String unescapeJson(final String input); // public static final String escapeHtml4(final String input); // public static final String escapeHtml3(final String input); // public static final String unescapeHtml4(final String input); // public static final String unescapeHtml3(final String input); // public static final String escapeXml(final String input); // public static final String unescapeXml(final String input); // public static final String escapeCsv(final String input); // public static final String unescapeCsv(final String input); // @Override // public int translate(final CharSequence input, final int index, final Writer out) throws IOException; // @Override // public int translate(final CharSequence input, final int index, final Writer out) throws IOException; // } // // // Abstract Java Test Class // package org.apache.commons.lang3; // // import static org.junit.Assert.assertEquals; // import static org.junit.Assert.assertFalse; // import static org.junit.Assert.assertNotNull; // import static org.junit.Assert.assertTrue; // import static org.junit.Assert.fail; // import java.io.FileInputStream; // import java.io.IOException; // import java.io.StringWriter; // import java.lang.reflect.Constructor; // import java.lang.reflect.Modifier; // import org.apache.commons.io.IOUtils; // import org.apache.commons.lang3.text.translate.CharSequenceTranslator; // import org.apache.commons.lang3.text.translate.NumericEntityEscaper; // import org.junit.Test; // // // // public class StringEscapeUtilsTest { // private final static String FOO = "foo"; // private static final String[][] HTML_ESCAPES = { // {"no escaping", "plain text", "plain text"}, // {"no escaping", "plain text", "plain text"}, // {"empty string", "", ""}, // {"null", null, null}, // {"ampersand", "bread &amp; butter", "bread & butter"}, // {"quotes", "&quot;bread&quot; &amp; butter", "\"bread\" & butter"}, // {"final character only", "greater than &gt;", "greater than >"}, // {"first character only", "&lt; less than", "< less than"}, // {"apostrophe", "Huntington's chorea", "Huntington's chorea"}, // {"languages", "English,Fran&ccedil;ais,\u65E5\u672C\u8A9E (nihongo)", "English,Fran\u00E7ais,\u65E5\u672C\u8A9E (nihongo)"}, // {"8-bit ascii shouldn't number-escape", "\u0080\u009F", "\u0080\u009F"}, // }; // // @Test // public void testConstructor(); // @Test // public void testEscapeJava() throws IOException; // @Test // public void testEscapeJavaWithSlash(); // private void assertEscapeJava(final String escaped, final String original) throws IOException; // private void assertEscapeJava(String message, final String expected, final String original) throws IOException; // @Test // public void testUnescapeJava() throws IOException; // private void assertUnescapeJava(final String unescaped, final String original) throws IOException; // private void assertUnescapeJava(final String message, final String unescaped, final String original) throws IOException; // @Test // public void testEscapeEcmaScript(); // @Test // public void testEscapeHtml(); // @Test // public void testUnescapeHtml4(); // @Test // public void testUnescapeHexCharsHtml(); // @Test // public void testUnescapeUnknownEntity() throws Exception; // @Test // public void testEscapeHtmlVersions() throws Exception; // @Test // public void testEscapeXml() throws Exception; // @Test // public void testEscapeXmlSupplementaryCharacters(); // @Test // public void testEscapeXmlAllCharacters(); // @Test // public void testUnescapeXmlSupplementaryCharacters(); // @Test // public void testStandaloneAmphersand(); // @Test // public void testLang313(); // @Test // public void testEscapeCsvString() throws Exception; // @Test // public void testEscapeCsvWriter() throws Exception; // private void checkCsvEscapeWriter(final String expected, final String value); // @Test // public void testUnescapeCsvString() throws Exception; // @Test // public void testUnescapeCsvWriter() throws Exception; // private void checkCsvUnescapeWriter(final String expected, final String value); // @Test // public void testEscapeHtmlHighUnicode() throws java.io.UnsupportedEncodingException; // @Test // public void testEscapeHiragana(); // @Test // public void testLang708() throws IOException; // @Test // public void testLang720(); // @Test // public void testEscapeJson(); // } // You are a professional Java test case writer, please create a test case named `testEscapeHtmlHighUnicode` for the `StringEscapeUtils` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests // https://issues.apache.org/jira/browse/LANG-480 * * @throws java.io.UnsupportedEncodingException */ @Test public void testEscapeHtmlHighUnicode() throws java.io.UnsupportedEncodingException {
/** * Tests // https://issues.apache.org/jira/browse/LANG-480 * * @throws java.io.UnsupportedEncodingException */
1
org.apache.commons.lang3.StringEscapeUtils
src/test/java
```java public static final CharSequenceTranslator UNESCAPE_HTML3 = new AggregateTranslator( new LookupTranslator(EntityArrays.BASIC_UNESCAPE()), new LookupTranslator(EntityArrays.ISO8859_1_UNESCAPE()), new NumericEntityUnescaper() ); public static final CharSequenceTranslator UNESCAPE_HTML4 = new AggregateTranslator( new LookupTranslator(EntityArrays.BASIC_UNESCAPE()), new LookupTranslator(EntityArrays.ISO8859_1_UNESCAPE()), new LookupTranslator(EntityArrays.HTML40_EXTENDED_UNESCAPE()), new NumericEntityUnescaper() ); public static final CharSequenceTranslator UNESCAPE_XML = new AggregateTranslator( new LookupTranslator(EntityArrays.BASIC_UNESCAPE()), new LookupTranslator(EntityArrays.APOS_UNESCAPE()), new NumericEntityUnescaper() ); public static final CharSequenceTranslator UNESCAPE_CSV = new CsvUnescaper(); public StringEscapeUtils(); public static final String escapeJava(final String input); public static final String escapeEcmaScript(final String input); public static final String escapeJson(final String input); public static final String unescapeJava(final String input); public static final String unescapeEcmaScript(final String input); public static final String unescapeJson(final String input); public static final String escapeHtml4(final String input); public static final String escapeHtml3(final String input); public static final String unescapeHtml4(final String input); public static final String unescapeHtml3(final String input); public static final String escapeXml(final String input); public static final String unescapeXml(final String input); public static final String escapeCsv(final String input); public static final String unescapeCsv(final String input); @Override public int translate(final CharSequence input, final int index, final Writer out) throws IOException; @Override public int translate(final CharSequence input, final int index, final Writer out) throws IOException; } // Abstract Java Test Class package org.apache.commons.lang3; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.FileInputStream; import java.io.IOException; import java.io.StringWriter; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.text.translate.CharSequenceTranslator; import org.apache.commons.lang3.text.translate.NumericEntityEscaper; import org.junit.Test; public class StringEscapeUtilsTest { private final static String FOO = "foo"; private static final String[][] HTML_ESCAPES = { {"no escaping", "plain text", "plain text"}, {"no escaping", "plain text", "plain text"}, {"empty string", "", ""}, {"null", null, null}, {"ampersand", "bread &amp; butter", "bread & butter"}, {"quotes", "&quot;bread&quot; &amp; butter", "\"bread\" & butter"}, {"final character only", "greater than &gt;", "greater than >"}, {"first character only", "&lt; less than", "< less than"}, {"apostrophe", "Huntington's chorea", "Huntington's chorea"}, {"languages", "English,Fran&ccedil;ais,\u65E5\u672C\u8A9E (nihongo)", "English,Fran\u00E7ais,\u65E5\u672C\u8A9E (nihongo)"}, {"8-bit ascii shouldn't number-escape", "\u0080\u009F", "\u0080\u009F"}, }; @Test public void testConstructor(); @Test public void testEscapeJava() throws IOException; @Test public void testEscapeJavaWithSlash(); private void assertEscapeJava(final String escaped, final String original) throws IOException; private void assertEscapeJava(String message, final String expected, final String original) throws IOException; @Test public void testUnescapeJava() throws IOException; private void assertUnescapeJava(final String unescaped, final String original) throws IOException; private void assertUnescapeJava(final String message, final String unescaped, final String original) throws IOException; @Test public void testEscapeEcmaScript(); @Test public void testEscapeHtml(); @Test public void testUnescapeHtml4(); @Test public void testUnescapeHexCharsHtml(); @Test public void testUnescapeUnknownEntity() throws Exception; @Test public void testEscapeHtmlVersions() throws Exception; @Test public void testEscapeXml() throws Exception; @Test public void testEscapeXmlSupplementaryCharacters(); @Test public void testEscapeXmlAllCharacters(); @Test public void testUnescapeXmlSupplementaryCharacters(); @Test public void testStandaloneAmphersand(); @Test public void testLang313(); @Test public void testEscapeCsvString() throws Exception; @Test public void testEscapeCsvWriter() throws Exception; private void checkCsvEscapeWriter(final String expected, final String value); @Test public void testUnescapeCsvString() throws Exception; @Test public void testUnescapeCsvWriter() throws Exception; private void checkCsvUnescapeWriter(final String expected, final String value); @Test public void testEscapeHtmlHighUnicode() throws java.io.UnsupportedEncodingException; @Test public void testEscapeHiragana(); @Test public void testLang708() throws IOException; @Test public void testLang720(); @Test public void testEscapeJson(); } ``` You are a professional Java test case writer, please create a test case named `testEscapeHtmlHighUnicode` for the `StringEscapeUtils` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests // https://issues.apache.org/jira/browse/LANG-480 * * @throws java.io.UnsupportedEncodingException */ @Test public void testEscapeHtmlHighUnicode() throws java.io.UnsupportedEncodingException { ```
public class StringEscapeUtils
package org.apache.commons.lang3; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.FileInputStream; import java.io.IOException; import java.io.StringWriter; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.text.translate.CharSequenceTranslator; import org.apache.commons.lang3.text.translate.NumericEntityEscaper; import org.junit.Test;
@Test public void testConstructor(); @Test public void testEscapeJava() throws IOException; @Test public void testEscapeJavaWithSlash(); private void assertEscapeJava(final String escaped, final String original) throws IOException; private void assertEscapeJava(String message, final String expected, final String original) throws IOException; @Test public void testUnescapeJava() throws IOException; private void assertUnescapeJava(final String unescaped, final String original) throws IOException; private void assertUnescapeJava(final String message, final String unescaped, final String original) throws IOException; @Test public void testEscapeEcmaScript(); @Test public void testEscapeHtml(); @Test public void testUnescapeHtml4(); @Test public void testUnescapeHexCharsHtml(); @Test public void testUnescapeUnknownEntity() throws Exception; @Test public void testEscapeHtmlVersions() throws Exception; @Test public void testEscapeXml() throws Exception; @Test public void testEscapeXmlSupplementaryCharacters(); @Test public void testEscapeXmlAllCharacters(); @Test public void testUnescapeXmlSupplementaryCharacters(); @Test public void testStandaloneAmphersand(); @Test public void testLang313(); @Test public void testEscapeCsvString() throws Exception; @Test public void testEscapeCsvWriter() throws Exception; private void checkCsvEscapeWriter(final String expected, final String value); @Test public void testUnescapeCsvString() throws Exception; @Test public void testUnescapeCsvWriter() throws Exception; private void checkCsvUnescapeWriter(final String expected, final String value); @Test public void testEscapeHtmlHighUnicode() throws java.io.UnsupportedEncodingException; @Test public void testEscapeHiragana(); @Test public void testLang708() throws IOException; @Test public void testLang720(); @Test public void testEscapeJson();
19d86d33e834bfe9cd6be4a4cfc09c55dedd0105e4618f30bc05e773c3d2f69f
[ "org.apache.commons.lang3.StringEscapeUtilsTest::testEscapeHtmlHighUnicode" ]
public static final CharSequenceTranslator ESCAPE_JAVA = new LookupTranslator( new String[][] { {"\"", "\\\""}, {"\\", "\\\\"}, }).with( new LookupTranslator(EntityArrays.JAVA_CTRL_CHARS_ESCAPE()) ).with( JavaUnicodeEscaper.outsideOf(32, 0x7f) ); public static final CharSequenceTranslator ESCAPE_ECMASCRIPT = new AggregateTranslator( new LookupTranslator( new String[][] { {"'", "\\'"}, {"\"", "\\\""}, {"\\", "\\\\"}, {"/", "\\/"} }), new LookupTranslator(EntityArrays.JAVA_CTRL_CHARS_ESCAPE()), JavaUnicodeEscaper.outsideOf(32, 0x7f) ); public static final CharSequenceTranslator ESCAPE_JSON = new AggregateTranslator( new LookupTranslator( new String[][] { {"\"", "\\\""}, {"\\", "\\\\"}, {"/", "\\/"} }), new LookupTranslator(EntityArrays.JAVA_CTRL_CHARS_ESCAPE()), JavaUnicodeEscaper.outsideOf(32, 0x7f) ); public static final CharSequenceTranslator ESCAPE_XML = new AggregateTranslator( new LookupTranslator(EntityArrays.BASIC_ESCAPE()), new LookupTranslator(EntityArrays.APOS_ESCAPE()) ); public static final CharSequenceTranslator ESCAPE_HTML3 = new AggregateTranslator( new LookupTranslator(EntityArrays.BASIC_ESCAPE()), new LookupTranslator(EntityArrays.ISO8859_1_ESCAPE()) ); public static final CharSequenceTranslator ESCAPE_HTML4 = new AggregateTranslator( new LookupTranslator(EntityArrays.BASIC_ESCAPE()), new LookupTranslator(EntityArrays.ISO8859_1_ESCAPE()), new LookupTranslator(EntityArrays.HTML40_EXTENDED_ESCAPE()) ); public static final CharSequenceTranslator ESCAPE_CSV = new CsvEscaper(); public static final CharSequenceTranslator UNESCAPE_JAVA = new AggregateTranslator( new OctalUnescaper(), // .between('\1', '\377'), new UnicodeUnescaper(), new LookupTranslator(EntityArrays.JAVA_CTRL_CHARS_UNESCAPE()), new LookupTranslator( new String[][] { {"\\\\", "\\"}, {"\\\"", "\""}, {"\\'", "'"}, {"\\", ""} }) ); public static final CharSequenceTranslator UNESCAPE_ECMASCRIPT = UNESCAPE_JAVA; public static final CharSequenceTranslator UNESCAPE_JSON = UNESCAPE_JAVA; public static final CharSequenceTranslator UNESCAPE_HTML3 = new AggregateTranslator( new LookupTranslator(EntityArrays.BASIC_UNESCAPE()), new LookupTranslator(EntityArrays.ISO8859_1_UNESCAPE()), new NumericEntityUnescaper() ); public static final CharSequenceTranslator UNESCAPE_HTML4 = new AggregateTranslator( new LookupTranslator(EntityArrays.BASIC_UNESCAPE()), new LookupTranslator(EntityArrays.ISO8859_1_UNESCAPE()), new LookupTranslator(EntityArrays.HTML40_EXTENDED_UNESCAPE()), new NumericEntityUnescaper() ); public static final CharSequenceTranslator UNESCAPE_XML = new AggregateTranslator( new LookupTranslator(EntityArrays.BASIC_UNESCAPE()), new LookupTranslator(EntityArrays.APOS_UNESCAPE()), new NumericEntityUnescaper() ); public static final CharSequenceTranslator UNESCAPE_CSV = new CsvUnescaper();
@Test public void testEscapeHtmlHighUnicode() throws java.io.UnsupportedEncodingException
private final static String FOO = "foo"; private static final String[][] HTML_ESCAPES = { {"no escaping", "plain text", "plain text"}, {"no escaping", "plain text", "plain text"}, {"empty string", "", ""}, {"null", null, null}, {"ampersand", "bread &amp; butter", "bread & butter"}, {"quotes", "&quot;bread&quot; &amp; butter", "\"bread\" & butter"}, {"final character only", "greater than &gt;", "greater than >"}, {"first character only", "&lt; less than", "< less than"}, {"apostrophe", "Huntington's chorea", "Huntington's chorea"}, {"languages", "English,Fran&ccedil;ais,\u65E5\u672C\u8A9E (nihongo)", "English,Fran\u00E7ais,\u65E5\u672C\u8A9E (nihongo)"}, {"8-bit ascii shouldn't number-escape", "\u0080\u009F", "\u0080\u009F"}, };
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; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.FileInputStream; import java.io.IOException; import java.io.StringWriter; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.text.translate.CharSequenceTranslator; import org.apache.commons.lang3.text.translate.NumericEntityEscaper; import org.junit.Test; /** * Unit tests for {@link StringEscapeUtils}. * * @version $Id$ */ public class StringEscapeUtilsTest { private final static String FOO = "foo"; @Test public void testConstructor() { assertNotNull(new StringEscapeUtils()); final Constructor<?>[] cons = StringEscapeUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertTrue(Modifier.isPublic(cons[0].getModifiers())); assertTrue(Modifier.isPublic(StringEscapeUtils.class.getModifiers())); assertFalse(Modifier.isFinal(StringEscapeUtils.class.getModifiers())); } @Test public void testEscapeJava() throws IOException { assertEquals(null, StringEscapeUtils.escapeJava(null)); try { StringEscapeUtils.ESCAPE_JAVA.translate(null, null); fail(); } catch (final IOException ex) { fail(); } catch (final IllegalArgumentException ex) { } try { StringEscapeUtils.ESCAPE_JAVA.translate("", null); fail(); } catch (final IOException ex) { fail(); } catch (final IllegalArgumentException ex) { } assertEscapeJava("empty string", "", ""); assertEscapeJava(FOO, FOO); assertEscapeJava("tab", "\\t", "\t"); assertEscapeJava("backslash", "\\\\", "\\"); assertEscapeJava("single quote should not be escaped", "'", "'"); assertEscapeJava("\\\\\\b\\t\\r", "\\\b\t\r"); assertEscapeJava("\\u1234", "\u1234"); assertEscapeJava("\\u0234", "\u0234"); assertEscapeJava("\\u00EF", "\u00ef"); assertEscapeJava("\\u0001", "\u0001"); assertEscapeJava("Should use capitalized Unicode hex", "\\uABCD", "\uabcd"); assertEscapeJava("He didn't say, \\\"stop!\\\"", "He didn't say, \"stop!\""); assertEscapeJava("non-breaking space", "This space is non-breaking:" + "\\u00A0", "This space is non-breaking:\u00a0"); assertEscapeJava("\\uABCD\\u1234\\u012C", "\uABCD\u1234\u012C"); } /** * Tests https://issues.apache.org/jira/browse/LANG-421 */ @Test public void testEscapeJavaWithSlash() { final String input = "String with a slash (/) in it"; final String expected = input; final String actual = StringEscapeUtils.escapeJava(input); /** * In 2.4 StringEscapeUtils.escapeJava(String) escapes '/' characters, which are not a valid character to escape * in a Java string. */ assertEquals(expected, actual); } private void assertEscapeJava(final String escaped, final String original) throws IOException { assertEscapeJava(null, escaped, original); } private void assertEscapeJava(String message, final String expected, final String original) throws IOException { final String converted = StringEscapeUtils.escapeJava(original); message = "escapeJava(String) failed" + (message == null ? "" : (": " + message)); assertEquals(message, expected, converted); final StringWriter writer = new StringWriter(); StringEscapeUtils.ESCAPE_JAVA.translate(original, writer); assertEquals(expected, writer.toString()); } @Test public void testUnescapeJava() throws IOException { assertEquals(null, StringEscapeUtils.unescapeJava(null)); try { StringEscapeUtils.UNESCAPE_JAVA.translate(null, null); fail(); } catch (final IOException ex) { fail(); } catch (final IllegalArgumentException ex) { } try { StringEscapeUtils.UNESCAPE_JAVA.translate("", null); fail(); } catch (final IOException ex) { fail(); } catch (final IllegalArgumentException ex) { } try { StringEscapeUtils.unescapeJava("\\u02-3"); fail(); } catch (final RuntimeException ex) { } assertUnescapeJava("", ""); assertUnescapeJava("test", "test"); assertUnescapeJava("\ntest\b", "\\ntest\\b"); assertUnescapeJava("\u123425foo\ntest\b", "\\u123425foo\\ntest\\b"); assertUnescapeJava("'\foo\teste\r", "\\'\\foo\\teste\\r"); assertUnescapeJava("", "\\"); //foo assertUnescapeJava("lowercase Unicode", "\uABCDx", "\\uabcdx"); assertUnescapeJava("uppercase Unicode", "\uABCDx", "\\uABCDx"); assertUnescapeJava("Unicode as final character", "\uABCD", "\\uabcd"); } private void assertUnescapeJava(final String unescaped, final String original) throws IOException { assertUnescapeJava(null, unescaped, original); } private void assertUnescapeJava(final String message, final String unescaped, final String original) throws IOException { final String expected = unescaped; final String actual = StringEscapeUtils.unescapeJava(original); assertEquals("unescape(String) failed" + (message == null ? "" : (": " + message)) + ": expected '" + StringEscapeUtils.escapeJava(expected) + // we escape this so we can see it in the error message "' actual '" + StringEscapeUtils.escapeJava(actual) + "'", expected, actual); final StringWriter writer = new StringWriter(); StringEscapeUtils.UNESCAPE_JAVA.translate(original, writer); assertEquals(unescaped, writer.toString()); } @Test public void testEscapeEcmaScript() { assertEquals(null, StringEscapeUtils.escapeEcmaScript(null)); try { StringEscapeUtils.ESCAPE_ECMASCRIPT.translate(null, null); fail(); } catch (final IOException ex) { fail(); } catch (final IllegalArgumentException ex) { } try { StringEscapeUtils.ESCAPE_ECMASCRIPT.translate("", null); fail(); } catch (final IOException ex) { fail(); } catch (final IllegalArgumentException ex) { } assertEquals("He didn\\'t say, \\\"stop!\\\"", StringEscapeUtils.escapeEcmaScript("He didn't say, \"stop!\"")); assertEquals("document.getElementById(\\\"test\\\").value = \\'<script>alert(\\'aaa\\');<\\/script>\\';", StringEscapeUtils.escapeEcmaScript("document.getElementById(\"test\").value = '<script>alert('aaa');</script>';")); } // HTML and XML //-------------------------------------------------------------- private static final String[][] HTML_ESCAPES = { {"no escaping", "plain text", "plain text"}, {"no escaping", "plain text", "plain text"}, {"empty string", "", ""}, {"null", null, null}, {"ampersand", "bread &amp; butter", "bread & butter"}, {"quotes", "&quot;bread&quot; &amp; butter", "\"bread\" & butter"}, {"final character only", "greater than &gt;", "greater than >"}, {"first character only", "&lt; less than", "< less than"}, {"apostrophe", "Huntington's chorea", "Huntington's chorea"}, {"languages", "English,Fran&ccedil;ais,\u65E5\u672C\u8A9E (nihongo)", "English,Fran\u00E7ais,\u65E5\u672C\u8A9E (nihongo)"}, {"8-bit ascii shouldn't number-escape", "\u0080\u009F", "\u0080\u009F"}, }; @Test public void testEscapeHtml() { for (int i = 0; i < HTML_ESCAPES.length; ++i) { final String message = HTML_ESCAPES[i][0]; final String expected = HTML_ESCAPES[i][1]; final String original = HTML_ESCAPES[i][2]; assertEquals(message, expected, StringEscapeUtils.escapeHtml4(original)); final StringWriter sw = new StringWriter(); try { StringEscapeUtils.ESCAPE_HTML4.translate(original, sw); } catch (final IOException e) { } final String actual = original == null ? null : sw.toString(); assertEquals(message, expected, actual); } } @Test public void testUnescapeHtml4() { for (int i = 0; i < HTML_ESCAPES.length; ++i) { final String message = HTML_ESCAPES[i][0]; final String expected = HTML_ESCAPES[i][2]; final String original = HTML_ESCAPES[i][1]; assertEquals(message, expected, StringEscapeUtils.unescapeHtml4(original)); final StringWriter sw = new StringWriter(); try { StringEscapeUtils.UNESCAPE_HTML4.translate(original, sw); } catch (final IOException e) { } final String actual = original == null ? null : sw.toString(); assertEquals(message, expected, actual); } // \u00E7 is a cedilla (c with wiggle under) // note that the test string must be 7-bit-clean (Unicode escaped) or else it will compile incorrectly // on some locales assertEquals("funny chars pass through OK", "Fran\u00E7ais", StringEscapeUtils.unescapeHtml4("Fran\u00E7ais")); assertEquals("Hello&;World", StringEscapeUtils.unescapeHtml4("Hello&;World")); assertEquals("Hello&#;World", StringEscapeUtils.unescapeHtml4("Hello&#;World")); assertEquals("Hello&# ;World", StringEscapeUtils.unescapeHtml4("Hello&# ;World")); assertEquals("Hello&##;World", StringEscapeUtils.unescapeHtml4("Hello&##;World")); } @Test public void testUnescapeHexCharsHtml() { // Simple easy to grok test assertEquals("hex number unescape", "\u0080\u009F", StringEscapeUtils.unescapeHtml4("&#x80;&#x9F;")); assertEquals("hex number unescape", "\u0080\u009F", StringEscapeUtils.unescapeHtml4("&#X80;&#X9F;")); // Test all Character values: for (char i = Character.MIN_VALUE; i < Character.MAX_VALUE; i++) { final Character c1 = new Character(i); final Character c2 = new Character((char)(i+1)); final String expected = c1.toString() + c2.toString(); final String escapedC1 = "&#x" + Integer.toHexString((c1.charValue())) + ";"; final String escapedC2 = "&#x" + Integer.toHexString((c2.charValue())) + ";"; assertEquals("hex number unescape index " + (int)i, expected, StringEscapeUtils.unescapeHtml4(escapedC1 + escapedC2)); } } @Test public void testUnescapeUnknownEntity() throws Exception { assertEquals("&zzzz;", StringEscapeUtils.unescapeHtml4("&zzzz;")); } @Test public void testEscapeHtmlVersions() throws Exception { assertEquals("&Beta;", StringEscapeUtils.escapeHtml4("\u0392")); assertEquals("\u0392", StringEscapeUtils.unescapeHtml4("&Beta;")); // TODO: refine API for escaping/unescaping specific HTML versions } @Test public void testEscapeXml() throws Exception { assertEquals("&lt;abc&gt;", StringEscapeUtils.escapeXml("<abc>")); assertEquals("<abc>", StringEscapeUtils.unescapeXml("&lt;abc&gt;")); assertEquals("XML should not escape >0x7f values", "\u00A1", StringEscapeUtils.escapeXml("\u00A1")); assertEquals("XML should be able to unescape >0x7f values", "\u00A0", StringEscapeUtils.unescapeXml("&#160;")); assertEquals("XML should be able to unescape >0x7f values with one leading 0", "\u00A0", StringEscapeUtils.unescapeXml("&#0160;")); assertEquals("XML should be able to unescape >0x7f values with two leading 0s", "\u00A0", StringEscapeUtils.unescapeXml("&#00160;")); assertEquals("XML should be able to unescape >0x7f values with three leading 0s", "\u00A0", StringEscapeUtils.unescapeXml("&#000160;")); assertEquals("ain't", StringEscapeUtils.unescapeXml("ain&apos;t")); assertEquals("ain&apos;t", StringEscapeUtils.escapeXml("ain't")); assertEquals("", StringEscapeUtils.escapeXml("")); assertEquals(null, StringEscapeUtils.escapeXml(null)); assertEquals(null, StringEscapeUtils.unescapeXml(null)); StringWriter sw = new StringWriter(); try { StringEscapeUtils.ESCAPE_XML.translate("<abc>", sw); } catch (final IOException e) { } assertEquals("XML was escaped incorrectly", "&lt;abc&gt;", sw.toString() ); sw = new StringWriter(); try { StringEscapeUtils.UNESCAPE_XML.translate("&lt;abc&gt;", sw); } catch (final IOException e) { } assertEquals("XML was unescaped incorrectly", "<abc>", sw.toString() ); } /** * Tests Supplementary characters. * <p> * From http://www.w3.org/International/questions/qa-escapes * </p> * <blockquote> * Supplementary characters are those Unicode characters that have code points higher than the characters in * the Basic Multilingual Plane (BMP). In UTF-16 a supplementary character is encoded using two 16-bit surrogate code points from the * BMP. Because of this, some people think that supplementary characters need to be represented using two escapes, but this is incorrect * - you must use the single, code point value for that character. For example, use &#x233B4; rather than &#xD84C;&#xDFB4;. * </blockquote> * @see <a href="http://www.w3.org/International/questions/qa-escapes">Using character escapes in markup and CSS</a> * @see <a href="https://issues.apache.org/jira/browse/LANG-728">LANG-728</a> */ @Test public void testEscapeXmlSupplementaryCharacters() { final CharSequenceTranslator escapeXml = StringEscapeUtils.ESCAPE_XML.with( NumericEntityEscaper.between(0x7f, Integer.MAX_VALUE) ); assertEquals("Supplementary character must be represented using a single escape", "&#144308;", escapeXml.translate("\uD84C\uDFB4")); } @Test public void testEscapeXmlAllCharacters() { // http://www.w3.org/TR/xml/#charsets says: // Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character, // excluding the surrogate blocks, FFFE, and FFFF. */ final CharSequenceTranslator escapeXml = StringEscapeUtils.ESCAPE_XML .with(NumericEntityEscaper.below(9), NumericEntityEscaper.between(0xB, 0xC), NumericEntityEscaper.between(0xE, 0x19), NumericEntityEscaper.between(0xD800, 0xDFFF), NumericEntityEscaper.between(0xFFFE, 0xFFFF), NumericEntityEscaper.above(0x110000)); assertEquals("&#0;&#1;&#2;&#3;&#4;&#5;&#6;&#7;&#8;", escapeXml.translate("\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008")); assertEquals("\t", escapeXml.translate("\t")); // 0x9 assertEquals("\n", escapeXml.translate("\n")); // 0xA assertEquals("&#11;&#12;", escapeXml.translate("\u000B\u000C")); assertEquals("\r", escapeXml.translate("\r")); // 0xD assertEquals("Hello World! Ain&apos;t this great?", escapeXml.translate("Hello World! Ain't this great?")); assertEquals("&#14;&#15;&#24;&#25;", escapeXml.translate("\u000E\u000F\u0018\u0019")); } /** * Reverse of the above. * * @see <a href="https://issues.apache.org/jira/browse/LANG-729">LANG-729</a> */ @Test public void testUnescapeXmlSupplementaryCharacters() { assertEquals("Supplementary character must be represented using a single escape", "\uD84C\uDFB4", StringEscapeUtils.unescapeXml("&#144308;") ); } // Tests issue #38569 // http://issues.apache.org/bugzilla/show_bug.cgi?id=38569 @Test public void testStandaloneAmphersand() { assertEquals("<P&O>", StringEscapeUtils.unescapeHtml4("&lt;P&O&gt;")); assertEquals("test & <", StringEscapeUtils.unescapeHtml4("test & &lt;")); assertEquals("<P&O>", StringEscapeUtils.unescapeXml("&lt;P&O&gt;")); assertEquals("test & <", StringEscapeUtils.unescapeXml("test & &lt;")); } @Test public void testLang313() { assertEquals("& &", StringEscapeUtils.unescapeHtml4("& &amp;")); } @Test public void testEscapeCsvString() throws Exception { assertEquals("foo.bar", StringEscapeUtils.escapeCsv("foo.bar")); assertEquals("\"foo,bar\"", StringEscapeUtils.escapeCsv("foo,bar")); assertEquals("\"foo\nbar\"", StringEscapeUtils.escapeCsv("foo\nbar")); assertEquals("\"foo\rbar\"", StringEscapeUtils.escapeCsv("foo\rbar")); assertEquals("\"foo\"\"bar\"", StringEscapeUtils.escapeCsv("foo\"bar")); assertEquals("", StringEscapeUtils.escapeCsv("")); assertEquals(null, StringEscapeUtils.escapeCsv(null)); } @Test public void testEscapeCsvWriter() throws Exception { checkCsvEscapeWriter("foo.bar", "foo.bar"); checkCsvEscapeWriter("\"foo,bar\"", "foo,bar"); checkCsvEscapeWriter("\"foo\nbar\"", "foo\nbar"); checkCsvEscapeWriter("\"foo\rbar\"", "foo\rbar"); checkCsvEscapeWriter("\"foo\"\"bar\"", "foo\"bar"); checkCsvEscapeWriter("", null); checkCsvEscapeWriter("", ""); } private void checkCsvEscapeWriter(final String expected, final String value) { try { final StringWriter writer = new StringWriter(); StringEscapeUtils.ESCAPE_CSV.translate(value, writer); assertEquals(expected, writer.toString()); } catch (final IOException e) { fail("Threw: " + e); } } @Test public void testUnescapeCsvString() throws Exception { assertEquals("foo.bar", StringEscapeUtils.unescapeCsv("foo.bar")); assertEquals("foo,bar", StringEscapeUtils.unescapeCsv("\"foo,bar\"")); assertEquals("foo\nbar", StringEscapeUtils.unescapeCsv("\"foo\nbar\"")); assertEquals("foo\rbar", StringEscapeUtils.unescapeCsv("\"foo\rbar\"")); assertEquals("foo\"bar", StringEscapeUtils.unescapeCsv("\"foo\"\"bar\"")); assertEquals("", StringEscapeUtils.unescapeCsv("")); assertEquals(null, StringEscapeUtils.unescapeCsv(null)); assertEquals("\"foo.bar\"", StringEscapeUtils.unescapeCsv("\"foo.bar\"")); } @Test public void testUnescapeCsvWriter() throws Exception { checkCsvUnescapeWriter("foo.bar", "foo.bar"); checkCsvUnescapeWriter("foo,bar", "\"foo,bar\""); checkCsvUnescapeWriter("foo\nbar", "\"foo\nbar\""); checkCsvUnescapeWriter("foo\rbar", "\"foo\rbar\""); checkCsvUnescapeWriter("foo\"bar", "\"foo\"\"bar\""); checkCsvUnescapeWriter("", null); checkCsvUnescapeWriter("", ""); checkCsvUnescapeWriter("\"foo.bar\"", "\"foo.bar\""); } private void checkCsvUnescapeWriter(final String expected, final String value) { try { final StringWriter writer = new StringWriter(); StringEscapeUtils.UNESCAPE_CSV.translate(value, writer); assertEquals(expected, writer.toString()); } catch (final IOException e) { fail("Threw: " + e); } } /** * Tests // https://issues.apache.org/jira/browse/LANG-480 * * @throws java.io.UnsupportedEncodingException */ @Test public void testEscapeHtmlHighUnicode() throws java.io.UnsupportedEncodingException { // this is the utf8 representation of the character: // COUNTING ROD UNIT DIGIT THREE // in Unicode // codepoint: U+1D362 final byte[] data = new byte[] { (byte)0xF0, (byte)0x9D, (byte)0x8D, (byte)0xA2 }; final String original = new String(data, "UTF8"); final String escaped = StringEscapeUtils.escapeHtml4( original ); assertEquals( "High Unicode should not have been escaped", original, escaped); final String unescaped = StringEscapeUtils.unescapeHtml4( escaped ); assertEquals( "High Unicode should have been unchanged", original, unescaped); // TODO: I think this should hold, needs further investigation // String unescapedFromEntity = StringEscapeUtils.unescapeHtml4( "&#119650;" ); // assertEquals( "High Unicode should have been unescaped", original, unescapedFromEntity); } /** * Tests https://issues.apache.org/jira/browse/LANG-339 */ @Test public void testEscapeHiragana() { // Some random Japanese Unicode characters final String original = "\u304B\u304C\u3068"; final String escaped = StringEscapeUtils.escapeHtml4(original); assertEquals( "Hiragana character Unicode behaviour should not be being escaped by escapeHtml4", original, escaped); final String unescaped = StringEscapeUtils.unescapeHtml4( escaped ); assertEquals( "Hiragana character Unicode behaviour has changed - expected no unescaping", escaped, unescaped); } /** * Tests https://issues.apache.org/jira/browse/LANG-708 * * @throws IOException * if an I/O error occurs */ @Test public void testLang708() throws IOException { final String input = IOUtils.toString(new FileInputStream("src/test/resources/lang-708-input.txt"), "UTF-8"); final String escaped = StringEscapeUtils.escapeEcmaScript(input); // just the end: assertTrue(escaped, escaped.endsWith("}]")); // a little more: assertTrue(escaped, escaped.endsWith("\"valueCode\\\":\\\"\\\"}]")); } /** * Tests https://issues.apache.org/jira/browse/LANG-720 */ @Test public void testLang720() { final String input = new StringBuilder("\ud842\udfb7").append("A").toString(); final String escaped = StringEscapeUtils.escapeXml(input); assertEquals(input, escaped); } @Test public void testEscapeJson() { assertEquals(null, StringEscapeUtils.escapeJson(null)); try { StringEscapeUtils.ESCAPE_JSON.translate(null, null); fail(); } catch (final IOException ex) { fail(); } catch (final IllegalArgumentException ex) { } try { StringEscapeUtils.ESCAPE_JSON.translate("", null); fail(); } catch (final IOException ex) { fail(); } catch (final IllegalArgumentException ex) { } assertEquals("He didn't say, \\\"stop!\\\"", StringEscapeUtils.escapeJson("He didn't say, \"stop!\"")); String expected = "\\\"foo\\\" isn't \\\"bar\\\". specials: \\b\\r\\n\\f\\t\\\\\\/"; String input ="\"foo\" isn't \"bar\". specials: \b\r\n\f\t\\/"; assertEquals(expected, StringEscapeUtils.escapeJson(input)); } }
[ { "be_test_class_file": "org/apache/commons/lang3/StringEscapeUtils.java", "be_test_class_name": "org.apache.commons.lang3.StringEscapeUtils", "be_test_function_name": "escapeHtml4", "be_test_function_signature": "(Ljava/lang/String;)Ljava/lang/String;", "line_numbers": [ "511" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/StringEscapeUtils.java", "be_test_class_name": "org.apache.commons.lang3.StringEscapeUtils", "be_test_function_name": "unescapeHtml4", "be_test_function_signature": "(Ljava/lang/String;)Ljava/lang/String;", "line_numbers": [ "546" ], "method_line_rate": 1 } ]
public class DatasetUtilitiesTests extends TestCase
public void testCreateCategoryDataset2() { boolean pass = false; String[] rowKeys = {"R1", "R2", "R3"}; String[] columnKeys = {"C1", "C2"}; double[][] data = new double[2][]; data[0] = new double[] {1.1, 1.2, 1.3}; data[1] = new double[] {2.1, 2.2, 2.3}; CategoryDataset dataset = null; try { dataset = DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, data); } catch (IllegalArgumentException e) { pass = true; // got it! } assertTrue(pass); assertTrue(dataset == null); }
// public static Range iterateRangeBounds(XYDataset dataset, // boolean includeInterval); // public static Range iterateToFindDomainBounds(XYDataset dataset, // List visibleSeriesKeys, boolean includeInterval); // public static Range iterateToFindRangeBounds(XYDataset dataset, // List visibleSeriesKeys, Range xRange, boolean includeInterval); // public static Number findMinimumDomainValue(XYDataset dataset); // public static Number findMaximumDomainValue(XYDataset dataset); // public static Number findMinimumRangeValue(CategoryDataset dataset); // public static Number findMinimumRangeValue(XYDataset dataset); // public static Number findMaximumRangeValue(CategoryDataset dataset); // public static Number findMaximumRangeValue(XYDataset dataset); // public static Range findStackedRangeBounds(CategoryDataset dataset); // public static Range findStackedRangeBounds(CategoryDataset dataset, // double base); // public static Range findStackedRangeBounds(CategoryDataset dataset, // KeyToGroupMap map); // public static Number findMinimumStackedRangeValue(CategoryDataset dataset); // public static Number findMaximumStackedRangeValue(CategoryDataset dataset); // public static Range findStackedRangeBounds(TableXYDataset dataset); // public static Range findStackedRangeBounds(TableXYDataset dataset, // double base); // public static double calculateStackTotal(TableXYDataset dataset, int item); // public static Range findCumulativeRangeBounds(CategoryDataset dataset); // } // // // Abstract Java Test Class // package org.jfree.data.general.junit; // // import java.util.ArrayList; // import java.util.Arrays; // import java.util.Date; // import java.util.List; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.data.KeyToGroupMap; // import org.jfree.data.Range; // import org.jfree.data.category.CategoryDataset; // import org.jfree.data.category.DefaultCategoryDataset; // import org.jfree.data.category.DefaultIntervalCategoryDataset; // import org.jfree.data.function.Function2D; // import org.jfree.data.function.LineFunction2D; // import org.jfree.data.general.DatasetUtilities; // import org.jfree.data.pie.DefaultPieDataset; // import org.jfree.data.pie.PieDataset; // import org.jfree.data.statistics.BoxAndWhiskerItem; // import org.jfree.data.statistics.DefaultBoxAndWhiskerXYDataset; // import org.jfree.data.statistics.DefaultMultiValueCategoryDataset; // import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; // import org.jfree.data.statistics.MultiValueCategoryDataset; // import org.jfree.data.xy.DefaultIntervalXYDataset; // import org.jfree.data.xy.DefaultTableXYDataset; // import org.jfree.data.xy.DefaultXYDataset; // import org.jfree.data.xy.IntervalXYDataset; // import org.jfree.data.xy.TableXYDataset; // import org.jfree.data.xy.XYDataset; // import org.jfree.data.xy.XYIntervalSeries; // import org.jfree.data.xy.XYIntervalSeriesCollection; // import org.jfree.data.xy.XYSeries; // import org.jfree.data.xy.XYSeriesCollection; // import org.jfree.data.xy.YIntervalSeries; // import org.jfree.data.xy.YIntervalSeriesCollection; // // // // public class DatasetUtilitiesTests extends TestCase { // private static final double EPSILON = 0.0000000001; // // public static Test suite(); // public DatasetUtilitiesTests(String name); // public void testJava(); // public void testCalculatePieDatasetTotal(); // public void testFindDomainBounds(); // public void testFindDomainBounds2(); // public void testFindDomainBounds3(); // public void testFindDomainBounds_NaN(); // public void testIterateDomainBounds(); // public void testIterateDomainBounds_NaN(); // public void testIterateDomainBounds_NaN2(); // public void testFindRangeBounds_CategoryDataset(); // public void testFindRangeBounds(); // public void testFindRangeBounds2(); // public void testIterateRangeBounds_CategoryDataset(); // public void testIterateRangeBounds2_CategoryDataset(); // public void testIterateRangeBounds3_CategoryDataset(); // public void testIterateRangeBounds(); // public void testIterateRangeBounds2(); // public void testIterateRangeBounds3(); // public void testIterateRangeBounds4(); // public void testFindMinimumDomainValue(); // public void testFindMaximumDomainValue(); // public void testFindMinimumRangeValue(); // public void testFindMaximumRangeValue(); // public void testMinMaxRange(); // public void test803660(); // public void testCumulativeRange1(); // public void testCumulativeRange2(); // public void testCumulativeRange3(); // public void testCumulativeRange_NaN(); // public void testCreateCategoryDataset1(); // public void testCreateCategoryDataset2(); // public void testMaximumStackedRangeValue(); // public void testFindStackedRangeBounds_CategoryDataset1(); // public void testFindStackedRangeBounds_CategoryDataset2(); // public void testFindStackedRangeBounds_CategoryDataset3(); // public void testFindStackedRangeBoundsForTableXYDataset1(); // public void testFindStackedRangeBoundsForTableXYDataset2(); // public void testStackedRangeWithMap(); // public void testIsEmptyOrNullXYDataset(); // public void testLimitPieDataset(); // public void testSampleFunction2D(); // public void testFindMinimumStackedRangeValue(); // public void testFindMinimumStackedRangeValue2(); // public void testFindMaximumStackedRangeValue(); // public void testFindMaximumStackedRangeValue2(); // private CategoryDataset createCategoryDataset1(); // private CategoryDataset createCategoryDataset2(); // private XYDataset createXYDataset1(); // private TableXYDataset createTableXYDataset1(); // public void testIterateToFindRangeBounds1_XYDataset(); // public void testIterateToFindRangeBounds2_XYDataset(); // public void testIterateToFindRangeBounds_BoxAndWhiskerXYDataset(); // public void testIterateToFindRangeBounds_StatisticalCategoryDataset(); // public void testIterateToFindRangeBounds_MultiValueCategoryDataset(); // public void testIterateRangeBounds_IntervalCategoryDataset(); // public void testBug2849731(); // public void testBug2849731_2(); // public void testBug2849731_3(); // } // You are a professional Java test case writer, please create a test case named `testCreateCategoryDataset2` for the `DatasetUtilities` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test the creation of a dataset from an array. This time is should fail * because the array dimensions are around the wrong way. */
tests/org/jfree/data/general/junit/DatasetUtilitiesTests.java
package org.jfree.data.general; import org.jfree.data.pie.PieDataset; import org.jfree.data.pie.DefaultPieDataset; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.jfree.chart.util.ArrayUtilities; import org.jfree.data.DomainInfo; import org.jfree.data.KeyToGroupMap; import org.jfree.data.KeyedValues; import org.jfree.data.Range; import org.jfree.data.RangeInfo; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.CategoryRangeInfo; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.category.IntervalCategoryDataset; import org.jfree.data.function.Function2D; import org.jfree.data.statistics.BoxAndWhiskerCategoryDataset; import org.jfree.data.statistics.BoxAndWhiskerXYDataset; import org.jfree.data.statistics.MultiValueCategoryDataset; import org.jfree.data.statistics.StatisticalCategoryDataset; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.OHLCDataset; import org.jfree.data.xy.TableXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYDomainInfo; import org.jfree.data.xy.XYRangeInfo; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection;
private DatasetUtilities(); public static double calculatePieDatasetTotal(PieDataset dataset); public static PieDataset createPieDatasetForRow(CategoryDataset dataset, Comparable rowKey); public static PieDataset createPieDatasetForRow(CategoryDataset dataset, int row); public static PieDataset createPieDatasetForColumn(CategoryDataset dataset, Comparable columnKey); public static PieDataset createPieDatasetForColumn(CategoryDataset dataset, int column); public static PieDataset createConsolidatedPieDataset(PieDataset source, Comparable key, double minimumPercent); public static PieDataset createConsolidatedPieDataset(PieDataset source, Comparable key, double minimumPercent, int minItems); public static CategoryDataset createCategoryDataset(String rowKeyPrefix, String columnKeyPrefix, double[][] data); public static CategoryDataset createCategoryDataset(String rowKeyPrefix, String columnKeyPrefix, Number[][] data); public static CategoryDataset createCategoryDataset(Comparable[] rowKeys, Comparable[] columnKeys, double[][] data); public static CategoryDataset createCategoryDataset(Comparable rowKey, KeyedValues rowData); public static XYDataset sampleFunction2D(Function2D f, double start, double end, int samples, Comparable seriesKey); public static XYSeries sampleFunction2DToSeries(Function2D f, double start, double end, int samples, Comparable seriesKey); public static boolean isEmptyOrNull(PieDataset dataset); public static boolean isEmptyOrNull(CategoryDataset dataset); public static boolean isEmptyOrNull(XYDataset dataset); public static Range findDomainBounds(XYDataset dataset); public static Range findDomainBounds(XYDataset dataset, boolean includeInterval); public static Range findDomainBounds(XYDataset dataset, List visibleSeriesKeys, boolean includeInterval); public static Range iterateDomainBounds(XYDataset dataset); public static Range iterateDomainBounds(XYDataset dataset, boolean includeInterval); public static Range findRangeBounds(CategoryDataset dataset); public static Range findRangeBounds(CategoryDataset dataset, boolean includeInterval); public static Range findRangeBounds(CategoryDataset dataset, List visibleSeriesKeys, boolean includeInterval); public static Range findRangeBounds(XYDataset dataset); public static Range findRangeBounds(XYDataset dataset, boolean includeInterval); public static Range findRangeBounds(XYDataset dataset, List visibleSeriesKeys, Range xRange, boolean includeInterval); public static Range iterateCategoryRangeBounds(CategoryDataset dataset, boolean includeInterval); public static Range iterateRangeBounds(CategoryDataset dataset); public static Range iterateRangeBounds(CategoryDataset dataset, boolean includeInterval); public static Range iterateToFindRangeBounds(CategoryDataset dataset, List visibleSeriesKeys, boolean includeInterval); public static Range iterateXYRangeBounds(XYDataset dataset); public static Range iterateRangeBounds(XYDataset dataset); public static Range iterateRangeBounds(XYDataset dataset, boolean includeInterval); public static Range iterateToFindDomainBounds(XYDataset dataset, List visibleSeriesKeys, boolean includeInterval); public static Range iterateToFindRangeBounds(XYDataset dataset, List visibleSeriesKeys, Range xRange, boolean includeInterval); public static Number findMinimumDomainValue(XYDataset dataset); public static Number findMaximumDomainValue(XYDataset dataset); public static Number findMinimumRangeValue(CategoryDataset dataset); public static Number findMinimumRangeValue(XYDataset dataset); public static Number findMaximumRangeValue(CategoryDataset dataset); public static Number findMaximumRangeValue(XYDataset dataset); public static Range findStackedRangeBounds(CategoryDataset dataset); public static Range findStackedRangeBounds(CategoryDataset dataset, double base); public static Range findStackedRangeBounds(CategoryDataset dataset, KeyToGroupMap map); public static Number findMinimumStackedRangeValue(CategoryDataset dataset); public static Number findMaximumStackedRangeValue(CategoryDataset dataset); public static Range findStackedRangeBounds(TableXYDataset dataset); public static Range findStackedRangeBounds(TableXYDataset dataset, double base); public static double calculateStackTotal(TableXYDataset dataset, int item); public static Range findCumulativeRangeBounds(CategoryDataset dataset);
656
testCreateCategoryDataset2
```java public static Range iterateRangeBounds(XYDataset dataset, boolean includeInterval); public static Range iterateToFindDomainBounds(XYDataset dataset, List visibleSeriesKeys, boolean includeInterval); public static Range iterateToFindRangeBounds(XYDataset dataset, List visibleSeriesKeys, Range xRange, boolean includeInterval); public static Number findMinimumDomainValue(XYDataset dataset); public static Number findMaximumDomainValue(XYDataset dataset); public static Number findMinimumRangeValue(CategoryDataset dataset); public static Number findMinimumRangeValue(XYDataset dataset); public static Number findMaximumRangeValue(CategoryDataset dataset); public static Number findMaximumRangeValue(XYDataset dataset); public static Range findStackedRangeBounds(CategoryDataset dataset); public static Range findStackedRangeBounds(CategoryDataset dataset, double base); public static Range findStackedRangeBounds(CategoryDataset dataset, KeyToGroupMap map); public static Number findMinimumStackedRangeValue(CategoryDataset dataset); public static Number findMaximumStackedRangeValue(CategoryDataset dataset); public static Range findStackedRangeBounds(TableXYDataset dataset); public static Range findStackedRangeBounds(TableXYDataset dataset, double base); public static double calculateStackTotal(TableXYDataset dataset, int item); public static Range findCumulativeRangeBounds(CategoryDataset dataset); } // Abstract Java Test Class package org.jfree.data.general.junit; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.KeyToGroupMap; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.category.DefaultIntervalCategoryDataset; import org.jfree.data.function.Function2D; import org.jfree.data.function.LineFunction2D; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.pie.DefaultPieDataset; import org.jfree.data.pie.PieDataset; import org.jfree.data.statistics.BoxAndWhiskerItem; import org.jfree.data.statistics.DefaultBoxAndWhiskerXYDataset; import org.jfree.data.statistics.DefaultMultiValueCategoryDataset; import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; import org.jfree.data.statistics.MultiValueCategoryDataset; import org.jfree.data.xy.DefaultIntervalXYDataset; import org.jfree.data.xy.DefaultTableXYDataset; import org.jfree.data.xy.DefaultXYDataset; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.TableXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYIntervalSeries; import org.jfree.data.xy.XYIntervalSeriesCollection; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.data.xy.YIntervalSeries; import org.jfree.data.xy.YIntervalSeriesCollection; public class DatasetUtilitiesTests extends TestCase { private static final double EPSILON = 0.0000000001; public static Test suite(); public DatasetUtilitiesTests(String name); public void testJava(); public void testCalculatePieDatasetTotal(); public void testFindDomainBounds(); public void testFindDomainBounds2(); public void testFindDomainBounds3(); public void testFindDomainBounds_NaN(); public void testIterateDomainBounds(); public void testIterateDomainBounds_NaN(); public void testIterateDomainBounds_NaN2(); public void testFindRangeBounds_CategoryDataset(); public void testFindRangeBounds(); public void testFindRangeBounds2(); public void testIterateRangeBounds_CategoryDataset(); public void testIterateRangeBounds2_CategoryDataset(); public void testIterateRangeBounds3_CategoryDataset(); public void testIterateRangeBounds(); public void testIterateRangeBounds2(); public void testIterateRangeBounds3(); public void testIterateRangeBounds4(); public void testFindMinimumDomainValue(); public void testFindMaximumDomainValue(); public void testFindMinimumRangeValue(); public void testFindMaximumRangeValue(); public void testMinMaxRange(); public void test803660(); public void testCumulativeRange1(); public void testCumulativeRange2(); public void testCumulativeRange3(); public void testCumulativeRange_NaN(); public void testCreateCategoryDataset1(); public void testCreateCategoryDataset2(); public void testMaximumStackedRangeValue(); public void testFindStackedRangeBounds_CategoryDataset1(); public void testFindStackedRangeBounds_CategoryDataset2(); public void testFindStackedRangeBounds_CategoryDataset3(); public void testFindStackedRangeBoundsForTableXYDataset1(); public void testFindStackedRangeBoundsForTableXYDataset2(); public void testStackedRangeWithMap(); public void testIsEmptyOrNullXYDataset(); public void testLimitPieDataset(); public void testSampleFunction2D(); public void testFindMinimumStackedRangeValue(); public void testFindMinimumStackedRangeValue2(); public void testFindMaximumStackedRangeValue(); public void testFindMaximumStackedRangeValue2(); private CategoryDataset createCategoryDataset1(); private CategoryDataset createCategoryDataset2(); private XYDataset createXYDataset1(); private TableXYDataset createTableXYDataset1(); public void testIterateToFindRangeBounds1_XYDataset(); public void testIterateToFindRangeBounds2_XYDataset(); public void testIterateToFindRangeBounds_BoxAndWhiskerXYDataset(); public void testIterateToFindRangeBounds_StatisticalCategoryDataset(); public void testIterateToFindRangeBounds_MultiValueCategoryDataset(); public void testIterateRangeBounds_IntervalCategoryDataset(); public void testBug2849731(); public void testBug2849731_2(); public void testBug2849731_3(); } ``` You are a professional Java test case writer, please create a test case named `testCreateCategoryDataset2` for the `DatasetUtilities` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test the creation of a dataset from an array. This time is should fail * because the array dimensions are around the wrong way. */
639
// public static Range iterateRangeBounds(XYDataset dataset, // boolean includeInterval); // public static Range iterateToFindDomainBounds(XYDataset dataset, // List visibleSeriesKeys, boolean includeInterval); // public static Range iterateToFindRangeBounds(XYDataset dataset, // List visibleSeriesKeys, Range xRange, boolean includeInterval); // public static Number findMinimumDomainValue(XYDataset dataset); // public static Number findMaximumDomainValue(XYDataset dataset); // public static Number findMinimumRangeValue(CategoryDataset dataset); // public static Number findMinimumRangeValue(XYDataset dataset); // public static Number findMaximumRangeValue(CategoryDataset dataset); // public static Number findMaximumRangeValue(XYDataset dataset); // public static Range findStackedRangeBounds(CategoryDataset dataset); // public static Range findStackedRangeBounds(CategoryDataset dataset, // double base); // public static Range findStackedRangeBounds(CategoryDataset dataset, // KeyToGroupMap map); // public static Number findMinimumStackedRangeValue(CategoryDataset dataset); // public static Number findMaximumStackedRangeValue(CategoryDataset dataset); // public static Range findStackedRangeBounds(TableXYDataset dataset); // public static Range findStackedRangeBounds(TableXYDataset dataset, // double base); // public static double calculateStackTotal(TableXYDataset dataset, int item); // public static Range findCumulativeRangeBounds(CategoryDataset dataset); // } // // // Abstract Java Test Class // package org.jfree.data.general.junit; // // import java.util.ArrayList; // import java.util.Arrays; // import java.util.Date; // import java.util.List; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.data.KeyToGroupMap; // import org.jfree.data.Range; // import org.jfree.data.category.CategoryDataset; // import org.jfree.data.category.DefaultCategoryDataset; // import org.jfree.data.category.DefaultIntervalCategoryDataset; // import org.jfree.data.function.Function2D; // import org.jfree.data.function.LineFunction2D; // import org.jfree.data.general.DatasetUtilities; // import org.jfree.data.pie.DefaultPieDataset; // import org.jfree.data.pie.PieDataset; // import org.jfree.data.statistics.BoxAndWhiskerItem; // import org.jfree.data.statistics.DefaultBoxAndWhiskerXYDataset; // import org.jfree.data.statistics.DefaultMultiValueCategoryDataset; // import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; // import org.jfree.data.statistics.MultiValueCategoryDataset; // import org.jfree.data.xy.DefaultIntervalXYDataset; // import org.jfree.data.xy.DefaultTableXYDataset; // import org.jfree.data.xy.DefaultXYDataset; // import org.jfree.data.xy.IntervalXYDataset; // import org.jfree.data.xy.TableXYDataset; // import org.jfree.data.xy.XYDataset; // import org.jfree.data.xy.XYIntervalSeries; // import org.jfree.data.xy.XYIntervalSeriesCollection; // import org.jfree.data.xy.XYSeries; // import org.jfree.data.xy.XYSeriesCollection; // import org.jfree.data.xy.YIntervalSeries; // import org.jfree.data.xy.YIntervalSeriesCollection; // // // // public class DatasetUtilitiesTests extends TestCase { // private static final double EPSILON = 0.0000000001; // // public static Test suite(); // public DatasetUtilitiesTests(String name); // public void testJava(); // public void testCalculatePieDatasetTotal(); // public void testFindDomainBounds(); // public void testFindDomainBounds2(); // public void testFindDomainBounds3(); // public void testFindDomainBounds_NaN(); // public void testIterateDomainBounds(); // public void testIterateDomainBounds_NaN(); // public void testIterateDomainBounds_NaN2(); // public void testFindRangeBounds_CategoryDataset(); // public void testFindRangeBounds(); // public void testFindRangeBounds2(); // public void testIterateRangeBounds_CategoryDataset(); // public void testIterateRangeBounds2_CategoryDataset(); // public void testIterateRangeBounds3_CategoryDataset(); // public void testIterateRangeBounds(); // public void testIterateRangeBounds2(); // public void testIterateRangeBounds3(); // public void testIterateRangeBounds4(); // public void testFindMinimumDomainValue(); // public void testFindMaximumDomainValue(); // public void testFindMinimumRangeValue(); // public void testFindMaximumRangeValue(); // public void testMinMaxRange(); // public void test803660(); // public void testCumulativeRange1(); // public void testCumulativeRange2(); // public void testCumulativeRange3(); // public void testCumulativeRange_NaN(); // public void testCreateCategoryDataset1(); // public void testCreateCategoryDataset2(); // public void testMaximumStackedRangeValue(); // public void testFindStackedRangeBounds_CategoryDataset1(); // public void testFindStackedRangeBounds_CategoryDataset2(); // public void testFindStackedRangeBounds_CategoryDataset3(); // public void testFindStackedRangeBoundsForTableXYDataset1(); // public void testFindStackedRangeBoundsForTableXYDataset2(); // public void testStackedRangeWithMap(); // public void testIsEmptyOrNullXYDataset(); // public void testLimitPieDataset(); // public void testSampleFunction2D(); // public void testFindMinimumStackedRangeValue(); // public void testFindMinimumStackedRangeValue2(); // public void testFindMaximumStackedRangeValue(); // public void testFindMaximumStackedRangeValue2(); // private CategoryDataset createCategoryDataset1(); // private CategoryDataset createCategoryDataset2(); // private XYDataset createXYDataset1(); // private TableXYDataset createTableXYDataset1(); // public void testIterateToFindRangeBounds1_XYDataset(); // public void testIterateToFindRangeBounds2_XYDataset(); // public void testIterateToFindRangeBounds_BoxAndWhiskerXYDataset(); // public void testIterateToFindRangeBounds_StatisticalCategoryDataset(); // public void testIterateToFindRangeBounds_MultiValueCategoryDataset(); // public void testIterateRangeBounds_IntervalCategoryDataset(); // public void testBug2849731(); // public void testBug2849731_2(); // public void testBug2849731_3(); // } // You are a professional Java test case writer, please create a test case named `testCreateCategoryDataset2` for the `DatasetUtilities` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test the creation of a dataset from an array. This time is should fail * because the array dimensions are around the wrong way. */ public void testCreateCategoryDataset2() {
/** * Test the creation of a dataset from an array. This time is should fail * because the array dimensions are around the wrong way. */
1
org.jfree.data.general.DatasetUtilities
tests
```java public static Range iterateRangeBounds(XYDataset dataset, boolean includeInterval); public static Range iterateToFindDomainBounds(XYDataset dataset, List visibleSeriesKeys, boolean includeInterval); public static Range iterateToFindRangeBounds(XYDataset dataset, List visibleSeriesKeys, Range xRange, boolean includeInterval); public static Number findMinimumDomainValue(XYDataset dataset); public static Number findMaximumDomainValue(XYDataset dataset); public static Number findMinimumRangeValue(CategoryDataset dataset); public static Number findMinimumRangeValue(XYDataset dataset); public static Number findMaximumRangeValue(CategoryDataset dataset); public static Number findMaximumRangeValue(XYDataset dataset); public static Range findStackedRangeBounds(CategoryDataset dataset); public static Range findStackedRangeBounds(CategoryDataset dataset, double base); public static Range findStackedRangeBounds(CategoryDataset dataset, KeyToGroupMap map); public static Number findMinimumStackedRangeValue(CategoryDataset dataset); public static Number findMaximumStackedRangeValue(CategoryDataset dataset); public static Range findStackedRangeBounds(TableXYDataset dataset); public static Range findStackedRangeBounds(TableXYDataset dataset, double base); public static double calculateStackTotal(TableXYDataset dataset, int item); public static Range findCumulativeRangeBounds(CategoryDataset dataset); } // Abstract Java Test Class package org.jfree.data.general.junit; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.KeyToGroupMap; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.category.DefaultIntervalCategoryDataset; import org.jfree.data.function.Function2D; import org.jfree.data.function.LineFunction2D; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.pie.DefaultPieDataset; import org.jfree.data.pie.PieDataset; import org.jfree.data.statistics.BoxAndWhiskerItem; import org.jfree.data.statistics.DefaultBoxAndWhiskerXYDataset; import org.jfree.data.statistics.DefaultMultiValueCategoryDataset; import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; import org.jfree.data.statistics.MultiValueCategoryDataset; import org.jfree.data.xy.DefaultIntervalXYDataset; import org.jfree.data.xy.DefaultTableXYDataset; import org.jfree.data.xy.DefaultXYDataset; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.TableXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYIntervalSeries; import org.jfree.data.xy.XYIntervalSeriesCollection; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.data.xy.YIntervalSeries; import org.jfree.data.xy.YIntervalSeriesCollection; public class DatasetUtilitiesTests extends TestCase { private static final double EPSILON = 0.0000000001; public static Test suite(); public DatasetUtilitiesTests(String name); public void testJava(); public void testCalculatePieDatasetTotal(); public void testFindDomainBounds(); public void testFindDomainBounds2(); public void testFindDomainBounds3(); public void testFindDomainBounds_NaN(); public void testIterateDomainBounds(); public void testIterateDomainBounds_NaN(); public void testIterateDomainBounds_NaN2(); public void testFindRangeBounds_CategoryDataset(); public void testFindRangeBounds(); public void testFindRangeBounds2(); public void testIterateRangeBounds_CategoryDataset(); public void testIterateRangeBounds2_CategoryDataset(); public void testIterateRangeBounds3_CategoryDataset(); public void testIterateRangeBounds(); public void testIterateRangeBounds2(); public void testIterateRangeBounds3(); public void testIterateRangeBounds4(); public void testFindMinimumDomainValue(); public void testFindMaximumDomainValue(); public void testFindMinimumRangeValue(); public void testFindMaximumRangeValue(); public void testMinMaxRange(); public void test803660(); public void testCumulativeRange1(); public void testCumulativeRange2(); public void testCumulativeRange3(); public void testCumulativeRange_NaN(); public void testCreateCategoryDataset1(); public void testCreateCategoryDataset2(); public void testMaximumStackedRangeValue(); public void testFindStackedRangeBounds_CategoryDataset1(); public void testFindStackedRangeBounds_CategoryDataset2(); public void testFindStackedRangeBounds_CategoryDataset3(); public void testFindStackedRangeBoundsForTableXYDataset1(); public void testFindStackedRangeBoundsForTableXYDataset2(); public void testStackedRangeWithMap(); public void testIsEmptyOrNullXYDataset(); public void testLimitPieDataset(); public void testSampleFunction2D(); public void testFindMinimumStackedRangeValue(); public void testFindMinimumStackedRangeValue2(); public void testFindMaximumStackedRangeValue(); public void testFindMaximumStackedRangeValue2(); private CategoryDataset createCategoryDataset1(); private CategoryDataset createCategoryDataset2(); private XYDataset createXYDataset1(); private TableXYDataset createTableXYDataset1(); public void testIterateToFindRangeBounds1_XYDataset(); public void testIterateToFindRangeBounds2_XYDataset(); public void testIterateToFindRangeBounds_BoxAndWhiskerXYDataset(); public void testIterateToFindRangeBounds_StatisticalCategoryDataset(); public void testIterateToFindRangeBounds_MultiValueCategoryDataset(); public void testIterateRangeBounds_IntervalCategoryDataset(); public void testBug2849731(); public void testBug2849731_2(); public void testBug2849731_3(); } ``` You are a professional Java test case writer, please create a test case named `testCreateCategoryDataset2` for the `DatasetUtilities` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test the creation of a dataset from an array. This time is should fail * because the array dimensions are around the wrong way. */ public void testCreateCategoryDataset2() { ```
public final class DatasetUtilities
package org.jfree.data.general.junit; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.KeyToGroupMap; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.category.DefaultIntervalCategoryDataset; import org.jfree.data.function.Function2D; import org.jfree.data.function.LineFunction2D; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.pie.DefaultPieDataset; import org.jfree.data.pie.PieDataset; import org.jfree.data.statistics.BoxAndWhiskerItem; import org.jfree.data.statistics.DefaultBoxAndWhiskerXYDataset; import org.jfree.data.statistics.DefaultMultiValueCategoryDataset; import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; import org.jfree.data.statistics.MultiValueCategoryDataset; import org.jfree.data.xy.DefaultIntervalXYDataset; import org.jfree.data.xy.DefaultTableXYDataset; import org.jfree.data.xy.DefaultXYDataset; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.TableXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYIntervalSeries; import org.jfree.data.xy.XYIntervalSeriesCollection; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.data.xy.YIntervalSeries; import org.jfree.data.xy.YIntervalSeriesCollection;
public static Test suite(); public DatasetUtilitiesTests(String name); public void testJava(); public void testCalculatePieDatasetTotal(); public void testFindDomainBounds(); public void testFindDomainBounds2(); public void testFindDomainBounds3(); public void testFindDomainBounds_NaN(); public void testIterateDomainBounds(); public void testIterateDomainBounds_NaN(); public void testIterateDomainBounds_NaN2(); public void testFindRangeBounds_CategoryDataset(); public void testFindRangeBounds(); public void testFindRangeBounds2(); public void testIterateRangeBounds_CategoryDataset(); public void testIterateRangeBounds2_CategoryDataset(); public void testIterateRangeBounds3_CategoryDataset(); public void testIterateRangeBounds(); public void testIterateRangeBounds2(); public void testIterateRangeBounds3(); public void testIterateRangeBounds4(); public void testFindMinimumDomainValue(); public void testFindMaximumDomainValue(); public void testFindMinimumRangeValue(); public void testFindMaximumRangeValue(); public void testMinMaxRange(); public void test803660(); public void testCumulativeRange1(); public void testCumulativeRange2(); public void testCumulativeRange3(); public void testCumulativeRange_NaN(); public void testCreateCategoryDataset1(); public void testCreateCategoryDataset2(); public void testMaximumStackedRangeValue(); public void testFindStackedRangeBounds_CategoryDataset1(); public void testFindStackedRangeBounds_CategoryDataset2(); public void testFindStackedRangeBounds_CategoryDataset3(); public void testFindStackedRangeBoundsForTableXYDataset1(); public void testFindStackedRangeBoundsForTableXYDataset2(); public void testStackedRangeWithMap(); public void testIsEmptyOrNullXYDataset(); public void testLimitPieDataset(); public void testSampleFunction2D(); public void testFindMinimumStackedRangeValue(); public void testFindMinimumStackedRangeValue2(); public void testFindMaximumStackedRangeValue(); public void testFindMaximumStackedRangeValue2(); private CategoryDataset createCategoryDataset1(); private CategoryDataset createCategoryDataset2(); private XYDataset createXYDataset1(); private TableXYDataset createTableXYDataset1(); public void testIterateToFindRangeBounds1_XYDataset(); public void testIterateToFindRangeBounds2_XYDataset(); public void testIterateToFindRangeBounds_BoxAndWhiskerXYDataset(); public void testIterateToFindRangeBounds_StatisticalCategoryDataset(); public void testIterateToFindRangeBounds_MultiValueCategoryDataset(); public void testIterateRangeBounds_IntervalCategoryDataset(); public void testBug2849731(); public void testBug2849731_2(); public void testBug2849731_3();
1be764d63e8890e41a257a35eb429bce26ef4a7756de4b96eb4895b9f2f1f35b
[ "org.jfree.data.general.junit.DatasetUtilitiesTests::testCreateCategoryDataset2" ]
public void testCreateCategoryDataset2()
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.] * * -------------------------- * DatasetUtilitiesTests.java * -------------------------- * (C) Copyright 2003-2009, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 18-Sep-2003 : Version 1 (DG); * 23-Mar-2004 : Added test for maximumStackedRangeValue() method (DG); * 04-Oct-2004 : Eliminated NumberUtils usage (DG); * 07-Jan-2005 : Updated for method name changes (DG); * 03-Feb-2005 : Added testFindStackedRangeBounds2() method (DG); * 26-Sep-2007 : Added testIsEmptyOrNullXYDataset() method (DG); * 28-Mar-2008 : Added and renamed various tests (DG); * 08-Oct-2008 : New tests to support patch 2131001 and related * changes (DG); * 25-Mar-2009 : Added tests for new iterateToFindRangeBounds() method (DG); * 16-May-2009 : Added * testIterateToFindRangeBounds_MultiValueCategoryDataset() (DG); * 10-Sep-2009 : Added tests for bug 2849731 (DG); * */ package org.jfree.data.general.junit; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.KeyToGroupMap; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.category.DefaultIntervalCategoryDataset; import org.jfree.data.function.Function2D; import org.jfree.data.function.LineFunction2D; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.pie.DefaultPieDataset; import org.jfree.data.pie.PieDataset; import org.jfree.data.statistics.BoxAndWhiskerItem; import org.jfree.data.statistics.DefaultBoxAndWhiskerXYDataset; import org.jfree.data.statistics.DefaultMultiValueCategoryDataset; import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; import org.jfree.data.statistics.MultiValueCategoryDataset; import org.jfree.data.xy.DefaultIntervalXYDataset; import org.jfree.data.xy.DefaultTableXYDataset; import org.jfree.data.xy.DefaultXYDataset; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.TableXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYIntervalSeries; import org.jfree.data.xy.XYIntervalSeriesCollection; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.data.xy.YIntervalSeries; import org.jfree.data.xy.YIntervalSeriesCollection; /** * Tests for the {@link DatasetUtilities} class. */ public class DatasetUtilitiesTests extends TestCase { private static final double EPSILON = 0.0000000001; /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(DatasetUtilitiesTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public DatasetUtilitiesTests(String name) { super(name); } /** * Some tests to verify that Java does what I think it does! */ public void testJava() { assertTrue(Double.isNaN(Math.min(1.0, Double.NaN))); assertTrue(Double.isNaN(Math.max(1.0, Double.NaN))); } /** * Some tests for the calculatePieDatasetTotal() method. */ public void testCalculatePieDatasetTotal() { DefaultPieDataset d = new DefaultPieDataset(); assertEquals(0.0, DatasetUtilities.calculatePieDatasetTotal(d), EPSILON); d.setValue("A", 1.0); assertEquals(1.0, DatasetUtilities.calculatePieDatasetTotal(d), EPSILON); d.setValue("B", 3.0); assertEquals(4.0, DatasetUtilities.calculatePieDatasetTotal(d), EPSILON); } /** * Some tests for the findDomainBounds() method. */ public void testFindDomainBounds() { XYDataset dataset = createXYDataset1(); Range r = DatasetUtilities.findDomainBounds(dataset); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(3.0, r.getUpperBound(), EPSILON); } /** * This test checks that the standard method has 'includeInterval' * defaulting to true. */ public void testFindDomainBounds2() { DefaultIntervalXYDataset dataset = new DefaultIntervalXYDataset(); double[] x1 = new double[] {1.0, 2.0, 3.0}; double[] x1Start = new double[] {0.9, 1.9, 2.9}; double[] x1End = new double[] {1.1, 2.1, 3.1}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[] y1Start = new double[] {1.09, 2.09, 3.09}; double[] y1End = new double[] {1.11, 2.11, 3.11}; double[][] data1 = new double[][] {x1, x1Start, x1End, y1, y1Start, y1End}; dataset.addSeries("S1", data1); Range r = DatasetUtilities.findDomainBounds(dataset); assertEquals(0.9, r.getLowerBound(), EPSILON); assertEquals(3.1, r.getUpperBound(), EPSILON); } /** * This test checks that when the 'includeInterval' flag is false, the * bounds come from the regular x-values. */ public void testFindDomainBounds3() { DefaultIntervalXYDataset dataset = new DefaultIntervalXYDataset(); double[] x1 = new double[] {1.0, 2.0, 3.0}; double[] x1Start = new double[] {0.9, 1.9, 2.9}; double[] x1End = new double[] {1.1, 2.1, 3.1}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[] y1Start = new double[] {1.09, 2.09, 3.09}; double[] y1End = new double[] {1.11, 2.11, 3.11}; double[][] data1 = new double[][] {x1, x1Start, x1End, y1, y1Start, y1End}; dataset.addSeries("S1", data1); Range r = DatasetUtilities.findDomainBounds(dataset, false); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(3.0, r.getUpperBound(), EPSILON); } /** * This test checks that NaN values are ignored. */ public void testFindDomainBounds_NaN() { DefaultIntervalXYDataset dataset = new DefaultIntervalXYDataset(); double[] x1 = new double[] {1.0, 2.0, Double.NaN}; double[] x1Start = new double[] {0.9, 1.9, Double.NaN}; double[] x1End = new double[] {1.1, 2.1, Double.NaN}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[] y1Start = new double[] {1.09, 2.09, 3.09}; double[] y1End = new double[] {1.11, 2.11, 3.11}; double[][] data1 = new double[][] {x1, x1Start, x1End, y1, y1Start, y1End}; dataset.addSeries("S1", data1); Range r = DatasetUtilities.findDomainBounds(dataset); assertEquals(0.9, r.getLowerBound(), EPSILON); assertEquals(2.1, r.getUpperBound(), EPSILON); r = DatasetUtilities.findDomainBounds(dataset, false); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(2.0, r.getUpperBound(), EPSILON); } /** * Some tests for the iterateDomainBounds() method. */ public void testIterateDomainBounds() { XYDataset dataset = createXYDataset1(); Range r = DatasetUtilities.iterateDomainBounds(dataset); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(3.0, r.getUpperBound(), EPSILON); } /** * Check that NaN values in the dataset are ignored. */ public void testIterateDomainBounds_NaN() { DefaultXYDataset dataset = new DefaultXYDataset(); double[] x = new double[] {1.0, 2.0, Double.NaN, 3.0}; double[] y = new double[] {9.0, 8.0, 7.0, 6.0}; dataset.addSeries("S1", new double[][] {x, y}); Range r = DatasetUtilities.iterateDomainBounds(dataset); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(3.0, r.getUpperBound(), EPSILON); } /** * Check that NaN values in the IntervalXYDataset are ignored. */ public void testIterateDomainBounds_NaN2() { DefaultIntervalXYDataset dataset = new DefaultIntervalXYDataset(); double[] x1 = new double[] {Double.NaN, 2.0, 3.0}; double[] x1Start = new double[] {0.9, Double.NaN, 2.9}; double[] x1End = new double[] {1.1, Double.NaN, 3.1}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[] y1Start = new double[] {1.09, 2.09, 3.09}; double[] y1End = new double[] {1.11, 2.11, 3.11}; double[][] data1 = new double[][] {x1, x1Start, x1End, y1, y1Start, y1End}; dataset.addSeries("S1", data1); Range r = DatasetUtilities.iterateDomainBounds(dataset, false); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(3.0, r.getUpperBound(), EPSILON); r = DatasetUtilities.iterateDomainBounds(dataset, true); assertEquals(0.9, r.getLowerBound(), EPSILON); assertEquals(3.1, r.getUpperBound(), EPSILON); } /** * Some tests for the findRangeBounds() for a CategoryDataset method. */ public void testFindRangeBounds_CategoryDataset() { CategoryDataset dataset = createCategoryDataset1(); Range r = DatasetUtilities.findRangeBounds(dataset); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(6.0, r.getUpperBound(), EPSILON); } /** * Some tests for the findRangeBounds() method on an XYDataset. */ public void testFindRangeBounds() { XYDataset dataset = createXYDataset1(); Range r = DatasetUtilities.findRangeBounds(dataset); assertEquals(100.0, r.getLowerBound(), EPSILON); assertEquals(105.0, r.getUpperBound(), EPSILON); } /** * A test for the findRangeBounds(XYDataset) method using * an IntervalXYDataset. */ public void testFindRangeBounds2() { YIntervalSeriesCollection dataset = new YIntervalSeriesCollection(); Range r = DatasetUtilities.findRangeBounds(dataset); assertNull(r); YIntervalSeries s1 = new YIntervalSeries("S1"); dataset.addSeries(s1); r = DatasetUtilities.findRangeBounds(dataset); assertNull(r); // try a single item s1.add(1.0, 2.0, 1.5, 2.5); r = DatasetUtilities.findRangeBounds(dataset); assertEquals(1.5, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); r = DatasetUtilities.findRangeBounds(dataset, false); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(2.0, r.getUpperBound(), EPSILON); // another item s1.add(2.0, 2.0, 1.4, 2.1); r = DatasetUtilities.findRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); // another empty series YIntervalSeries s2 = new YIntervalSeries("S2"); dataset.addSeries(s2); r = DatasetUtilities.findRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); // an item in series 2 s2.add(1.0, 2.0, 1.9, 2.6); r = DatasetUtilities.findRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.6, r.getUpperBound(), EPSILON); // what if we don't want the interval? r = DatasetUtilities.findRangeBounds(dataset, false); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(2.0, r.getUpperBound(), EPSILON); } /** * Some tests for the iterateRangeBounds() method. */ public void testIterateRangeBounds_CategoryDataset() { CategoryDataset dataset = createCategoryDataset1(); Range r = DatasetUtilities.iterateRangeBounds(dataset, false); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(6.0, r.getUpperBound(), EPSILON); } /** * Some checks for the iterateRangeBounds() method. */ public void testIterateRangeBounds2_CategoryDataset() { // an empty dataset should return a null range DefaultCategoryDataset dataset = new DefaultCategoryDataset(); Range r = DatasetUtilities.iterateRangeBounds(dataset, false); assertNull(r); // a dataset with a single value dataset.addValue(1.23, "R1", "C1"); r = DatasetUtilities.iterateRangeBounds(dataset, false); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); // null is ignored dataset.addValue(null, "R2", "C1"); r = DatasetUtilities.iterateRangeBounds(dataset, false); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); // a Double.NaN should be ignored dataset.addValue(Double.NaN, "R2", "C1"); r = DatasetUtilities.iterateRangeBounds(dataset, false); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); } /** * Some checks for the iterateRangeBounds() method using an * IntervalCategoryDataset. */ public void testIterateRangeBounds3_CategoryDataset() { Number[][] starts = new Double[2][3]; Number[][] ends = new Double[2][3]; starts[0][0] = new Double(1.0); starts[0][1] = new Double(2.0); starts[0][2] = new Double(3.0); starts[1][0] = new Double(11.0); starts[1][1] = new Double(12.0); starts[1][2] = new Double(13.0); ends[0][0] = new Double(4.0); ends[0][1] = new Double(5.0); ends[0][2] = new Double(6.0); ends[1][0] = new Double(16.0); ends[1][1] = new Double(15.0); ends[1][2] = new Double(14.0); DefaultIntervalCategoryDataset d = new DefaultIntervalCategoryDataset( starts, ends); Range r = DatasetUtilities.iterateRangeBounds(d, false); assertEquals(4.0, r.getLowerBound(), EPSILON); assertEquals(16.0, r.getUpperBound(), EPSILON); r = DatasetUtilities.iterateRangeBounds(d, true); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(16.0, r.getUpperBound(), EPSILON); } /** * Some tests for the iterateRangeBounds() method. */ public void testIterateRangeBounds() { XYDataset dataset = createXYDataset1(); Range r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(100.0, r.getLowerBound(), EPSILON); assertEquals(105.0, r.getUpperBound(), EPSILON); } /** * Check the range returned when a series contains a null value. */ public void testIterateRangeBounds2() { XYSeries s1 = new XYSeries("S1"); s1.add(1.0, 1.1); s1.add(2.0, null); s1.add(3.0, 3.3); XYSeriesCollection dataset = new XYSeriesCollection(s1); Range r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.1, r.getLowerBound(), EPSILON); assertEquals(3.3, r.getUpperBound(), EPSILON); } /** * Some checks for the iterateRangeBounds() method. */ public void testIterateRangeBounds3() { // an empty dataset should return a null range XYSeriesCollection dataset = new XYSeriesCollection(); Range r = DatasetUtilities.iterateRangeBounds(dataset); assertNull(r); XYSeries s1 = new XYSeries("S1"); dataset.addSeries(s1); r = DatasetUtilities.iterateRangeBounds(dataset); assertNull(r); // a dataset with a single value s1.add(1.0, 1.23); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); // null is ignored s1.add(2.0, null); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); // Double.NaN DOESN'T mess things up s1.add(3.0, Double.NaN); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); } /** * Some checks for the range bounds of a dataset that implements the * {@link IntervalXYDataset} interface. */ public void testIterateRangeBounds4() { YIntervalSeriesCollection dataset = new YIntervalSeriesCollection(); Range r = DatasetUtilities.iterateRangeBounds(dataset); assertNull(r); YIntervalSeries s1 = new YIntervalSeries("S1"); dataset.addSeries(s1); r = DatasetUtilities.iterateRangeBounds(dataset); assertNull(r); // try a single item s1.add(1.0, 2.0, 1.5, 2.5); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.5, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); // another item s1.add(2.0, 2.0, 1.4, 2.1); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); // another empty series YIntervalSeries s2 = new YIntervalSeries("S2"); dataset.addSeries(s2); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); // an item in series 2 s2.add(1.0, 2.0, 1.9, 2.6); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.6, r.getUpperBound(), EPSILON); } /** * Some tests for the findMinimumDomainValue() method. */ public void testFindMinimumDomainValue() { XYDataset dataset = createXYDataset1(); Number minimum = DatasetUtilities.findMinimumDomainValue(dataset); assertEquals(new Double(1.0), minimum); } /** * Some tests for the findMaximumDomainValue() method. */ public void testFindMaximumDomainValue() { XYDataset dataset = createXYDataset1(); Number maximum = DatasetUtilities.findMaximumDomainValue(dataset); assertEquals(new Double(3.0), maximum); } /** * Some tests for the findMinimumRangeValue() method. */ public void testFindMinimumRangeValue() { CategoryDataset d1 = createCategoryDataset1(); Number min1 = DatasetUtilities.findMinimumRangeValue(d1); assertEquals(new Double(1.0), min1); XYDataset d2 = createXYDataset1(); Number min2 = DatasetUtilities.findMinimumRangeValue(d2); assertEquals(new Double(100.0), min2); } /** * Some tests for the findMaximumRangeValue() method. */ public void testFindMaximumRangeValue() { CategoryDataset d1 = createCategoryDataset1(); Number max1 = DatasetUtilities.findMaximumRangeValue(d1); assertEquals(new Double(6.0), max1); XYDataset dataset = createXYDataset1(); Number maximum = DatasetUtilities.findMaximumRangeValue(dataset); assertEquals(new Double(105.0), maximum); } /** * A quick test of the min and max range value methods. */ public void testMinMaxRange() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(100.0, "Series 1", "Type 1"); dataset.addValue(101.1, "Series 1", "Type 2"); Number min = DatasetUtilities.findMinimumRangeValue(dataset); assertTrue(min.doubleValue() < 100.1); Number max = DatasetUtilities.findMaximumRangeValue(dataset); assertTrue(max.doubleValue() > 101.0); } /** * A test to reproduce bug report 803660. */ public void test803660() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(100.0, "Series 1", "Type 1"); dataset.addValue(101.1, "Series 1", "Type 2"); Number n = DatasetUtilities.findMaximumRangeValue(dataset); assertTrue(n.doubleValue() > 101.0); } /** * A simple test for the cumulative range calculation. The sequence of * "cumulative" values are considered to be { 0.0, 10.0, 25.0, 18.0 } so * the range should be 0.0 -> 25.0. */ public void testCumulativeRange1() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(10.0, "Series 1", "Start"); dataset.addValue(15.0, "Series 1", "Delta 1"); dataset.addValue(-7.0, "Series 1", "Delta 2"); Range range = DatasetUtilities.findCumulativeRangeBounds(dataset); assertEquals(0.0, range.getLowerBound(), 0.00000001); assertEquals(25.0, range.getUpperBound(), 0.00000001); } /** * A further test for the cumulative range calculation. */ public void testCumulativeRange2() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(-21.4, "Series 1", "Start Value"); dataset.addValue(11.57, "Series 1", "Delta 1"); dataset.addValue(3.51, "Series 1", "Delta 2"); dataset.addValue(-12.36, "Series 1", "Delta 3"); dataset.addValue(3.39, "Series 1", "Delta 4"); dataset.addValue(38.68, "Series 1", "Delta 5"); dataset.addValue(-43.31, "Series 1", "Delta 6"); dataset.addValue(-29.59, "Series 1", "Delta 7"); dataset.addValue(35.30, "Series 1", "Delta 8"); dataset.addValue(5.0, "Series 1", "Delta 9"); Range range = DatasetUtilities.findCumulativeRangeBounds(dataset); assertEquals(-49.51, range.getLowerBound(), 0.00000001); assertEquals(23.39, range.getUpperBound(), 0.00000001); } /** * A further test for the cumulative range calculation. */ public void testCumulativeRange3() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(15.76, "Product 1", "Labour"); dataset.addValue(8.66, "Product 1", "Administration"); dataset.addValue(4.71, "Product 1", "Marketing"); dataset.addValue(3.51, "Product 1", "Distribution"); dataset.addValue(32.64, "Product 1", "Total Expense"); Range range = DatasetUtilities.findCumulativeRangeBounds(dataset); assertEquals(0.0, range.getLowerBound(), EPSILON); assertEquals(65.28, range.getUpperBound(), EPSILON); } /** * Check that the findCumulativeRangeBounds() method ignores Double.NaN * values. */ public void testCumulativeRange_NaN() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(10.0, "Series 1", "Start"); dataset.addValue(15.0, "Series 1", "Delta 1"); dataset.addValue(Double.NaN, "Series 1", "Delta 2"); Range range = DatasetUtilities.findCumulativeRangeBounds(dataset); assertEquals(0.0, range.getLowerBound(), EPSILON); assertEquals(25.0, range.getUpperBound(), EPSILON); } /** * Test the creation of a dataset from an array. */ public void testCreateCategoryDataset1() { String[] rowKeys = {"R1", "R2", "R3"}; String[] columnKeys = {"C1", "C2"}; double[][] data = new double[3][]; data[0] = new double[] {1.1, 1.2}; data[1] = new double[] {2.1, 2.2}; data[2] = new double[] {3.1, 3.2}; CategoryDataset dataset = DatasetUtilities.createCategoryDataset( rowKeys, columnKeys, data); assertTrue(dataset.getRowCount() == 3); assertTrue(dataset.getColumnCount() == 2); } /** * Test the creation of a dataset from an array. This time is should fail * because the array dimensions are around the wrong way. */ public void testCreateCategoryDataset2() { boolean pass = false; String[] rowKeys = {"R1", "R2", "R3"}; String[] columnKeys = {"C1", "C2"}; double[][] data = new double[2][]; data[0] = new double[] {1.1, 1.2, 1.3}; data[1] = new double[] {2.1, 2.2, 2.3}; CategoryDataset dataset = null; try { dataset = DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, data); } catch (IllegalArgumentException e) { pass = true; // got it! } assertTrue(pass); assertTrue(dataset == null); } /** * Test for a bug reported in the forum: * * http://www.jfree.org/phpBB2/viewtopic.php?t=7903 */ public void testMaximumStackedRangeValue() { double v1 = 24.3; double v2 = 14.2; double v3 = 33.2; double v4 = 32.4; double v5 = 26.3; double v6 = 22.6; Number answer = new Double(Math.max(v1 + v2 + v3, v4 + v5 + v6)); DefaultCategoryDataset d = new DefaultCategoryDataset(); d.addValue(v1, "Row 0", "Column 0"); d.addValue(v2, "Row 1", "Column 0"); d.addValue(v3, "Row 2", "Column 0"); d.addValue(v4, "Row 0", "Column 1"); d.addValue(v5, "Row 1", "Column 1"); d.addValue(v6, "Row 2", "Column 1"); Number max = DatasetUtilities.findMaximumStackedRangeValue(d); assertTrue(max.equals(answer)); } /** * Some checks for the findStackedRangeBounds() method. */ public void testFindStackedRangeBounds_CategoryDataset1() { CategoryDataset d1 = createCategoryDataset1(); Range r = DatasetUtilities.findStackedRangeBounds(d1); assertEquals(0.0, r.getLowerBound(), EPSILON); assertEquals(15.0, r.getUpperBound(), EPSILON); d1 = createCategoryDataset2(); r = DatasetUtilities.findStackedRangeBounds(d1); assertEquals(-2.0, r.getLowerBound(), EPSILON); assertEquals(2.0, r.getUpperBound(), EPSILON); } /** * Some checks for the findStackedRangeBounds() method. */ public void testFindStackedRangeBounds_CategoryDataset2() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); Range r = DatasetUtilities.findStackedRangeBounds(dataset); assertTrue(r == null); dataset.addValue(5.0, "R1", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, 3.0); assertEquals(3.0, r.getLowerBound(), EPSILON); assertEquals(8.0, r.getUpperBound(), EPSILON); dataset.addValue(-1.0, "R2", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, 3.0); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(8.0, r.getUpperBound(), EPSILON); dataset.addValue(null, "R3", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, 3.0); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(8.0, r.getUpperBound(), EPSILON); dataset.addValue(Double.NaN, "R4", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, 3.0); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(8.0, r.getUpperBound(), EPSILON); } /** * Some checks for the findStackedRangeBounds(CategoryDataset, * KeyToGroupMap) method. */ public void testFindStackedRangeBounds_CategoryDataset3() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); KeyToGroupMap map = new KeyToGroupMap("Group A"); Range r = DatasetUtilities.findStackedRangeBounds(dataset, map); assertTrue(r == null); dataset.addValue(1.0, "R1", "C1"); dataset.addValue(2.0, "R2", "C1"); dataset.addValue(3.0, "R3", "C1"); dataset.addValue(4.0, "R4", "C1"); map.mapKeyToGroup("R1", "Group A"); map.mapKeyToGroup("R2", "Group A"); map.mapKeyToGroup("R3", "Group B"); map.mapKeyToGroup("R4", "Group B"); r = DatasetUtilities.findStackedRangeBounds(dataset, map); assertEquals(0.0, r.getLowerBound(), EPSILON); assertEquals(7.0, r.getUpperBound(), EPSILON); dataset.addValue(null, "R5", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, map); assertEquals(0.0, r.getLowerBound(), EPSILON); assertEquals(7.0, r.getUpperBound(), EPSILON); dataset.addValue(Double.NaN, "R6", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, map); assertEquals(0.0, r.getLowerBound(), EPSILON); assertEquals(7.0, r.getUpperBound(), EPSILON); } /** * Some checks for the findStackedRangeBounds() method. */ public void testFindStackedRangeBoundsForTableXYDataset1() { TableXYDataset d2 = createTableXYDataset1(); Range r = DatasetUtilities.findStackedRangeBounds(d2); assertEquals(-2.0, r.getLowerBound(), EPSILON); assertEquals(2.0, r.getUpperBound(), EPSILON); } /** * Some checks for the findStackedRangeBounds() method. */ public void testFindStackedRangeBoundsForTableXYDataset2() { DefaultTableXYDataset d = new DefaultTableXYDataset(); Range r = DatasetUtilities.findStackedRangeBounds(d); assertEquals(r, new Range(0.0, 0.0)); } /** * Tests the stacked range extent calculation. */ public void testStackedRangeWithMap() { CategoryDataset d = createCategoryDataset1(); KeyToGroupMap map = new KeyToGroupMap("G0"); map.mapKeyToGroup("R2", "G1"); Range r = DatasetUtilities.findStackedRangeBounds(d, map); assertEquals(0.0, r.getLowerBound(), EPSILON); assertEquals(9.0, r.getUpperBound(), EPSILON); } /** * Some checks for the isEmptyOrNull(XYDataset) method. */ public void testIsEmptyOrNullXYDataset() { XYSeriesCollection dataset = null; assertTrue(DatasetUtilities.isEmptyOrNull(dataset)); dataset = new XYSeriesCollection(); assertTrue(DatasetUtilities.isEmptyOrNull(dataset)); XYSeries s1 = new XYSeries("S1"); dataset.addSeries(s1); assertTrue(DatasetUtilities.isEmptyOrNull(dataset)); s1.add(1.0, 2.0); assertFalse(DatasetUtilities.isEmptyOrNull(dataset)); s1.clear(); assertTrue(DatasetUtilities.isEmptyOrNull(dataset)); } /** * Some checks for the limitPieDataset() methods. */ public void testLimitPieDataset() { // check that empty dataset is handled OK DefaultPieDataset d1 = new DefaultPieDataset(); PieDataset d2 = DatasetUtilities.createConsolidatedPieDataset(d1, "Other", 0.05); assertEquals(0, d2.getItemCount()); // check that minItem limit is observed d1.setValue("Item 1", 1.0); d1.setValue("Item 2", 49.50); d1.setValue("Item 3", 49.50); d2 = DatasetUtilities.createConsolidatedPieDataset(d1, "Other", 0.05); assertEquals(3, d2.getItemCount()); assertEquals("Item 1", d2.getKey(0)); assertEquals("Item 2", d2.getKey(1)); assertEquals("Item 3", d2.getKey(2)); // check that minItem limit is observed d1.setValue("Item 4", 1.0); d2 = DatasetUtilities.createConsolidatedPieDataset(d1, "Other", 0.05, 2); // and that simple aggregation works assertEquals(3, d2.getItemCount()); assertEquals("Item 2", d2.getKey(0)); assertEquals("Item 3", d2.getKey(1)); assertEquals("Other", d2.getKey(2)); assertEquals(new Double(2.0), d2.getValue("Other")); } /** * Some checks for the sampleFunction2D() method. */ public void testSampleFunction2D() { Function2D f = new LineFunction2D(0, 1); XYDataset dataset = DatasetUtilities.sampleFunction2D(f, 0.0, 1.0, 2, "S1"); assertEquals(1, dataset.getSeriesCount()); assertEquals("S1", dataset.getSeriesKey(0)); assertEquals(2, dataset.getItemCount(0)); assertEquals(0.0, dataset.getXValue(0, 0), EPSILON); assertEquals(0.0, dataset.getYValue(0, 0), EPSILON); assertEquals(1.0, dataset.getXValue(0, 1), EPSILON); assertEquals(1.0, dataset.getYValue(0, 1), EPSILON); } /** * A simple check for the findMinimumStackedRangeValue() method. */ public void testFindMinimumStackedRangeValue() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); // an empty dataset should return a null max Number min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertNull(min); dataset.addValue(1.0, "R1", "C1"); min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(0.0, min.doubleValue(), EPSILON); dataset.addValue(2.0, "R2", "C1"); min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(0.0, min.doubleValue(), EPSILON); dataset.addValue(-3.0, "R3", "C1"); min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(-3.0, min.doubleValue(), EPSILON); dataset.addValue(Double.NaN, "R4", "C1"); min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(-3.0, min.doubleValue(), EPSILON); } /** * A simple check for the findMaximumStackedRangeValue() method. */ public void testFindMinimumStackedRangeValue2() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(-1.0, "R1", "C1"); Number min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(-1.0, min.doubleValue(), EPSILON); dataset.addValue(-2.0, "R2", "C1"); min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(-3.0, min.doubleValue(), EPSILON); } /** * A simple check for the findMaximumStackedRangeValue() method. */ public void testFindMaximumStackedRangeValue() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); // an empty dataset should return a null max Number max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertNull(max); dataset.addValue(1.0, "R1", "C1"); max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(1.0, max.doubleValue(), EPSILON); dataset.addValue(2.0, "R2", "C1"); max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(3.0, max.doubleValue(), EPSILON); dataset.addValue(-3.0, "R3", "C1"); max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(3.0, max.doubleValue(), EPSILON); dataset.addValue(Double.NaN, "R4", "C1"); max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(3.0, max.doubleValue(), EPSILON); } /** * A simple check for the findMaximumStackedRangeValue() method. */ public void testFindMaximumStackedRangeValue2() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(-1.0, "R1", "C1"); Number max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(0.0, max.doubleValue(), EPSILON); dataset.addValue(-2.0, "R2", "C1"); max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(0.0, max.doubleValue(), EPSILON); } /** * Creates a dataset for testing. * * @return A dataset. */ private CategoryDataset createCategoryDataset1() { DefaultCategoryDataset result = new DefaultCategoryDataset(); result.addValue(1.0, "R0", "C0"); result.addValue(1.0, "R1", "C0"); result.addValue(1.0, "R2", "C0"); result.addValue(4.0, "R0", "C1"); result.addValue(5.0, "R1", "C1"); result.addValue(6.0, "R2", "C1"); return result; } /** * Creates a dataset for testing. * * @return A dataset. */ private CategoryDataset createCategoryDataset2() { DefaultCategoryDataset result = new DefaultCategoryDataset(); result.addValue(1.0, "R0", "C0"); result.addValue(-2.0, "R1", "C0"); result.addValue(2.0, "R0", "C1"); result.addValue(-1.0, "R1", "C1"); return result; } /** * Creates a dataset for testing. * * @return A dataset. */ private XYDataset createXYDataset1() { XYSeries series1 = new XYSeries("S1"); series1.add(1.0, 100.0); series1.add(2.0, 101.0); series1.add(3.0, 102.0); XYSeries series2 = new XYSeries("S2"); series2.add(1.0, 103.0); series2.add(2.0, null); series2.add(3.0, 105.0); XYSeriesCollection result = new XYSeriesCollection(); result.addSeries(series1); result.addSeries(series2); result.setIntervalWidth(0.0); return result; } /** * Creates a sample dataset for testing purposes. * * @return A sample dataset. */ private TableXYDataset createTableXYDataset1() { DefaultTableXYDataset dataset = new DefaultTableXYDataset(); XYSeries s1 = new XYSeries("Series 1", true, false); s1.add(1.0, 1.0); s1.add(2.0, 2.0); dataset.addSeries(s1); XYSeries s2 = new XYSeries("Series 2", true, false); s2.add(1.0, -2.0); s2.add(2.0, -1.0); dataset.addSeries(s2); return dataset; } /** * Some checks for the iteratorToFindRangeBounds(XYDataset...) method. */ public void testIterateToFindRangeBounds1_XYDataset() { // null dataset throws IllegalArgumentException boolean pass = false; try { DatasetUtilities.iterateToFindRangeBounds(null, new ArrayList(), new Range(0.0, 1.0), true); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); // null list throws IllegalArgumentException pass = false; try { DatasetUtilities.iterateToFindRangeBounds(new XYSeriesCollection(), null, new Range(0.0, 1.0), true); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); // null range throws IllegalArgumentException pass = false; try { DatasetUtilities.iterateToFindRangeBounds(new XYSeriesCollection(), new ArrayList(), null, true); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); } /** * Some tests for the iterateToFindRangeBounds() method. */ public void testIterateToFindRangeBounds2_XYDataset() { List visibleSeriesKeys = new ArrayList(); Range xRange = new Range(0.0, 10.0); // empty dataset returns null XYSeriesCollection dataset = new XYSeriesCollection(); Range r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertNull(r); // add an empty series XYSeries s1 = new XYSeries("A"); dataset.addSeries(s1); visibleSeriesKeys.add("A"); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertNull(r); // check a null value s1.add(1.0, null); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertNull(r); // check a NaN s1.add(2.0, Double.NaN); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertNull(r); // check a regular value s1.add(3.0, 5.0); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 5.0), r); // check another regular value s1.add(4.0, 6.0); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 6.0), r); // add a second series XYSeries s2 = new XYSeries("B"); dataset.addSeries(s2); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 6.0), r); visibleSeriesKeys.add("B"); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 6.0), r); // add a value to the second series s2.add(5.0, 15.0); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 15.0), r); // add a value that isn't in the xRange s2.add(15.0, 150.0); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 15.0), r); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, new Range(0.0, 20.0), false); assertEquals(new Range(5.0, 150.0), r); } /** * Some checks for the iterateToFindRangeBounds() method when applied to * a BoxAndWhiskerXYDataset. */ public void testIterateToFindRangeBounds_BoxAndWhiskerXYDataset() { DefaultBoxAndWhiskerXYDataset dataset = new DefaultBoxAndWhiskerXYDataset("Series 1"); List visibleSeriesKeys = new ArrayList(); visibleSeriesKeys.add("Series 1"); Range xRange = new Range(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); assertNull(DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false)); dataset.add(new Date(50L), new BoxAndWhiskerItem(5.0, 4.9, 2.0, 8.0, 1.0, 9.0, 0.0, 10.0, new ArrayList())); assertEquals(new Range(5.0, 5.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false)); assertEquals(new Range(1.0, 9.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, true)); } /** * Some checks for the iterateToFindRangeBounds(CategoryDataset...) * method. */ public void testIterateToFindRangeBounds_StatisticalCategoryDataset() { DefaultStatisticalCategoryDataset dataset = new DefaultStatisticalCategoryDataset(); List visibleSeriesKeys = new ArrayList(); assertNull(DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, false)); dataset.add(1.0, 0.5, "R1", "C1"); visibleSeriesKeys.add("R1"); assertEquals(new Range(1.0, 1.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, false)); assertEquals(new Range(0.5, 1.5), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); } /** * Some checks for the iterateToFindRangeBounds(CategoryDataset...) method * with a {@link MultiValueCategoryDataset}. */ public void testIterateToFindRangeBounds_MultiValueCategoryDataset() { DefaultMultiValueCategoryDataset dataset = new DefaultMultiValueCategoryDataset(); List visibleSeriesKeys = new ArrayList(); assertNull(DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); List values = Arrays.asList(new Double[] {new Double(1.0)}); dataset.add(values, "R1", "C1"); visibleSeriesKeys.add("R1"); assertEquals(new Range(1.0, 1.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); values = Arrays.asList(new Double[] {new Double(2.0), new Double(3.0)}); dataset.add(values, "R1", "C2"); assertEquals(new Range(1.0, 3.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); values = Arrays.asList(new Double[] {new Double(-1.0), new Double(-2.0)}); dataset.add(values, "R2", "C1"); assertEquals(new Range(1.0, 3.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); visibleSeriesKeys.add("R2"); assertEquals(new Range(-2.0, 3.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); } /** * Some checks for the iterateRangeBounds() method when passed an * IntervalCategoryDataset. */ public void testIterateRangeBounds_IntervalCategoryDataset() {} // Defects4J: flaky method // public void testIterateRangeBounds_IntervalCategoryDataset() { // TestIntervalCategoryDataset d = new TestIntervalCategoryDataset(); // d.addItem(1.0, 2.0, 3.0, "R1", "C1"); // assertEquals(new Range(1.0, 3.0), // DatasetUtilities.iterateRangeBounds(d)); // // d = new TestIntervalCategoryDataset(); // d.addItem(2.5, 2.0, 3.0, "R1", "C1"); // assertEquals(new Range(2.0, 3.0), // DatasetUtilities.iterateRangeBounds(d)); // // d = new TestIntervalCategoryDataset(); // d.addItem(4.0, 2.0, 3.0, "R1", "C1"); // assertEquals(new Range(2.0, 4.0), // DatasetUtilities.iterateRangeBounds(d)); // // d = new TestIntervalCategoryDataset(); // d.addItem(0.0, 2.0, 3.0, "R1", "C1"); // assertEquals(new Range(2.0, 3.0), // DatasetUtilities.iterateRangeBounds(d)); // // // try some nulls // d = new TestIntervalCategoryDataset(); // d.addItem(null, null, null, "R1", "C1"); // assertNull(DatasetUtilities.iterateRangeBounds(d)); // // d = new TestIntervalCategoryDataset(); // d.addItem(1.0, 0.0, 0.0, "R1", "C1"); // assertEquals(new Range(1.0, 1.0), // DatasetUtilities.iterateRangeBounds(d)); // // d = new TestIntervalCategoryDataset(); // d.addItem(0.0, 1.0, 0.0, "R1", "C1"); // assertEquals(new Range(1.0, 1.0), // DatasetUtilities.iterateRangeBounds(d)); // // d = new TestIntervalCategoryDataset(); // d.addItem(0.0, 0.0, 1.0, "R1", "C1"); // assertEquals(new Range(1.0, 1.0), // DatasetUtilities.iterateRangeBounds(d)); // } /** * A test for bug 2849731. */ public void testBug2849731() {} // Defects4J: flaky method // public void testBug2849731() { // TestIntervalCategoryDataset d = new TestIntervalCategoryDataset(); // d.addItem(2.5, 2.0, 3.0, "R1", "C1"); // d.addItem(4.0, 0.0, 0.0, "R2", "C1"); // assertEquals(new Range(2.0, 4.0), // DatasetUtilities.iterateRangeBounds(d)); // } /** * Another test for bug 2849731. */ public void testBug2849731_2() { XYIntervalSeriesCollection d = new XYIntervalSeriesCollection(); XYIntervalSeries s = new XYIntervalSeries("S1"); s.add(1.0, Double.NaN, Double.NaN, Double.NaN, 1.5, Double.NaN); d.addSeries(s); Range r = DatasetUtilities.iterateDomainBounds(d); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(1.0, r.getUpperBound(), EPSILON); s.add(1.0, 1.5, Double.NaN, Double.NaN, 1.5, Double.NaN); r = DatasetUtilities.iterateDomainBounds(d); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(1.5, r.getUpperBound(), EPSILON); s.add(1.0, Double.NaN, 0.5, Double.NaN, 1.5, Double.NaN); r = DatasetUtilities.iterateDomainBounds(d); assertEquals(0.5, r.getLowerBound(), EPSILON); assertEquals(1.5, r.getUpperBound(), EPSILON); } /** * Yet another test for bug 2849731. */ public void testBug2849731_3() { XYIntervalSeriesCollection d = new XYIntervalSeriesCollection(); XYIntervalSeries s = new XYIntervalSeries("S1"); s.add(1.0, Double.NaN, Double.NaN, 1.5, Double.NaN, Double.NaN); d.addSeries(s); Range r = DatasetUtilities.iterateRangeBounds(d); assertEquals(1.5, r.getLowerBound(), EPSILON); assertEquals(1.5, r.getUpperBound(), EPSILON); s.add(1.0, 1.5, Double.NaN, Double.NaN, Double.NaN, 2.5); r = DatasetUtilities.iterateRangeBounds(d); assertEquals(1.5, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); s.add(1.0, Double.NaN, 0.5, Double.NaN, 3.5, Double.NaN); r = DatasetUtilities.iterateRangeBounds(d); assertEquals(1.5, r.getLowerBound(), EPSILON); assertEquals(3.5, r.getUpperBound(), EPSILON); } }
[ { "be_test_class_file": "org/jfree/data/general/DatasetUtilities.java", "be_test_class_name": "org.jfree.data.general.DatasetUtilities", "be_test_function_name": "createCategoryDataset", "be_test_function_signature": "([Ljava/lang/Comparable;[Ljava/lang/Comparable;[[D)Lorg/jfree/data/category/CategoryDataset;", "line_numbers": [ "427", "428", "430", "431", "433", "434", "436", "437", "440", "441", "445", "446", "447", "449", "450", "456", "457", "458", "459", "460", "461", "464" ], "method_line_rate": 0.2727272727272727 } ]
public class ErfTest
@Test public void testErfcGnu() { final double tol = 1E-15; final double[] gnuValues = new double[] { 2, 2, 2, 2, 2, 2, 2, 2, 1.9999999999999999785, 1.9999999999999926422, 1.9999999999984625402, 1.9999999998033839558, 1.9999999845827420998, 1.9999992569016276586, 1.9999779095030014146, 1.9995930479825550411, 1.9953222650189527342, 1.9661051464753107271, 1.8427007929497148695, 1.5204998778130465381, 1, 0.47950012218695346194, 0.15729920705028513051, 0.033894853524689272893, 0.0046777349810472658333, 0.00040695201744495893941, 2.2090496998585441366E-05, 7.4309837234141274516E-07, 1.5417257900280018858E-08, 1.966160441542887477E-10, 1.5374597944280348501E-12, 7.3578479179743980661E-15, 2.1519736712498913103E-17, 3.8421483271206474691E-20, 4.1838256077794144006E-23, 2.7766493860305691016E-26, 1.1224297172982927079E-29, 2.7623240713337714448E-33, 4.1370317465138102353E-37, 3.7692144856548799402E-41, 2.0884875837625447567E-45}; double x = -10d; for (int i = 0; i < 41; i++) { Assert.assertEquals(gnuValues[i], Erf.erfc(x), tol); x += 0.5d; } }
// // Abstract Java Tested Class // package org.apache.commons.math3.special; // // import org.apache.commons.math3.util.FastMath; // // // // public class Erf { // private static final double X_CRIT = 0.4769362762044697; // // private Erf(); // public static double erf(double x); // public static double erfc(double x); // public static double erf(double x1, double x2); // public static double erfInv(final double x); // public static double erfcInv(final double x); // } // // // Abstract Java Test Class // package org.apache.commons.math3.special; // // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.util.FastMath; // import org.junit.Test; // import org.junit.Assert; // // // // public class ErfTest { // // // @Test // public void testErf0(); // @Test // public void testErf1960(); // @Test // public void testErf2576(); // @Test // public void testErf2807(); // @Test // public void testErf3291(); // @Test // public void testLargeValues(); // @Test // public void testErfGnu(); // @Test // public void testErfcGnu(); // @Test // public void testErfcMaple(); // @Test // public void testTwoArgumentErf(); // @Test // public void testErfInvNaN(); // @Test // public void testErfInvInfinite(); // @Test // public void testErfInv(); // @Test // public void testErfcInvNaN(); // @Test // public void testErfcInvInfinite(); // @Test // public void testErfcInv(); // } // You are a professional Java test case writer, please create a test case named `testErfcGnu` for the `Erf` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Compare Erf.erfc against reference values computed using GCC 4.2.1 (Apple OSX packaged version) * erfcl (extended precision erfc). */
src/test/java/org/apache/commons/math3/special/ErfTest.java
package org.apache.commons.math3.special; import org.apache.commons.math3.util.FastMath;
private Erf(); public static double erf(double x); public static double erfc(double x); public static double erf(double x1, double x2); public static double erfInv(final double x); public static double erfcInv(final double x);
164
testErfcGnu
```java // Abstract Java Tested Class package org.apache.commons.math3.special; import org.apache.commons.math3.util.FastMath; public class Erf { private static final double X_CRIT = 0.4769362762044697; private Erf(); public static double erf(double x); public static double erfc(double x); public static double erf(double x1, double x2); public static double erfInv(final double x); public static double erfcInv(final double x); } // Abstract Java Test Class package org.apache.commons.math3.special; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert; public class ErfTest { @Test public void testErf0(); @Test public void testErf1960(); @Test public void testErf2576(); @Test public void testErf2807(); @Test public void testErf3291(); @Test public void testLargeValues(); @Test public void testErfGnu(); @Test public void testErfcGnu(); @Test public void testErfcMaple(); @Test public void testTwoArgumentErf(); @Test public void testErfInvNaN(); @Test public void testErfInvInfinite(); @Test public void testErfInv(); @Test public void testErfcInvNaN(); @Test public void testErfcInvInfinite(); @Test public void testErfcInv(); } ``` You are a professional Java test case writer, please create a test case named `testErfcGnu` for the `Erf` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Compare Erf.erfc against reference values computed using GCC 4.2.1 (Apple OSX packaged version) * erfcl (extended precision erfc). */
146
// // Abstract Java Tested Class // package org.apache.commons.math3.special; // // import org.apache.commons.math3.util.FastMath; // // // // public class Erf { // private static final double X_CRIT = 0.4769362762044697; // // private Erf(); // public static double erf(double x); // public static double erfc(double x); // public static double erf(double x1, double x2); // public static double erfInv(final double x); // public static double erfcInv(final double x); // } // // // Abstract Java Test Class // package org.apache.commons.math3.special; // // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.util.FastMath; // import org.junit.Test; // import org.junit.Assert; // // // // public class ErfTest { // // // @Test // public void testErf0(); // @Test // public void testErf1960(); // @Test // public void testErf2576(); // @Test // public void testErf2807(); // @Test // public void testErf3291(); // @Test // public void testLargeValues(); // @Test // public void testErfGnu(); // @Test // public void testErfcGnu(); // @Test // public void testErfcMaple(); // @Test // public void testTwoArgumentErf(); // @Test // public void testErfInvNaN(); // @Test // public void testErfInvInfinite(); // @Test // public void testErfInv(); // @Test // public void testErfcInvNaN(); // @Test // public void testErfcInvInfinite(); // @Test // public void testErfcInv(); // } // You are a professional Java test case writer, please create a test case named `testErfcGnu` for the `Erf` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Compare Erf.erfc against reference values computed using GCC 4.2.1 (Apple OSX packaged version) * erfcl (extended precision erfc). */ @Test public void testErfcGnu() {
/** * Compare Erf.erfc against reference values computed using GCC 4.2.1 (Apple OSX packaged version) * erfcl (extended precision erfc). */
1
org.apache.commons.math3.special.Erf
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.math3.special; import org.apache.commons.math3.util.FastMath; public class Erf { private static final double X_CRIT = 0.4769362762044697; private Erf(); public static double erf(double x); public static double erfc(double x); public static double erf(double x1, double x2); public static double erfInv(final double x); public static double erfcInv(final double x); } // Abstract Java Test Class package org.apache.commons.math3.special; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert; public class ErfTest { @Test public void testErf0(); @Test public void testErf1960(); @Test public void testErf2576(); @Test public void testErf2807(); @Test public void testErf3291(); @Test public void testLargeValues(); @Test public void testErfGnu(); @Test public void testErfcGnu(); @Test public void testErfcMaple(); @Test public void testTwoArgumentErf(); @Test public void testErfInvNaN(); @Test public void testErfInvInfinite(); @Test public void testErfInv(); @Test public void testErfcInvNaN(); @Test public void testErfcInvInfinite(); @Test public void testErfcInv(); } ``` You are a professional Java test case writer, please create a test case named `testErfcGnu` for the `Erf` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Compare Erf.erfc against reference values computed using GCC 4.2.1 (Apple OSX packaged version) * erfcl (extended precision erfc). */ @Test public void testErfcGnu() { ```
public class Erf
package org.apache.commons.math3.special; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert;
@Test public void testErf0(); @Test public void testErf1960(); @Test public void testErf2576(); @Test public void testErf2807(); @Test public void testErf3291(); @Test public void testLargeValues(); @Test public void testErfGnu(); @Test public void testErfcGnu(); @Test public void testErfcMaple(); @Test public void testTwoArgumentErf(); @Test public void testErfInvNaN(); @Test public void testErfInvInfinite(); @Test public void testErfInv(); @Test public void testErfcInvNaN(); @Test public void testErfcInvInfinite(); @Test public void testErfcInv();
1ce03a6dccbc35426ff9c5d6d50393795d0d1c53f1831a8c7f4867e1c8cc1676
[ "org.apache.commons.math3.special.ErfTest::testErfcGnu" ]
private static final double X_CRIT = 0.4769362762044697;
@Test public void testErfcGnu()
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.special; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert; /** * @version $Id$ */ public class ErfTest { @Test public void testErf0() { double actual = Erf.erf(0.0); double expected = 0.0; Assert.assertEquals(expected, actual, 1.0e-15); Assert.assertEquals(1 - expected, Erf.erfc(0.0), 1.0e-15); } @Test public void testErf1960() { double x = 1.960 / FastMath.sqrt(2.0); double actual = Erf.erf(x); double expected = 0.95; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(x), 1.0e-15); actual = Erf.erf(-x); expected = -expected; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(-x), 1.0e-15); } @Test public void testErf2576() { double x = 2.576 / FastMath.sqrt(2.0); double actual = Erf.erf(x); double expected = 0.99; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(x), 1e-15); actual = Erf.erf(-x); expected = -expected; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(-x), 1.0e-15); } @Test public void testErf2807() { double x = 2.807 / FastMath.sqrt(2.0); double actual = Erf.erf(x); double expected = 0.995; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(x), 1.0e-15); actual = Erf.erf(-x); expected = -expected; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(-x), 1.0e-15); } @Test public void testErf3291() { double x = 3.291 / FastMath.sqrt(2.0); double actual = Erf.erf(x); double expected = 0.999; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - expected, Erf.erfc(x), 1.0e-5); actual = Erf.erf(-x); expected = -expected; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - expected, Erf.erfc(-x), 1.0e-5); } /** * MATH-301, MATH-456 */ @Test public void testLargeValues() { for (int i = 1; i < 200; i*=10) { double result = Erf.erf(i); Assert.assertFalse(Double.isNaN(result)); Assert.assertTrue(result > 0 && result <= 1); result = Erf.erf(-i); Assert.assertFalse(Double.isNaN(result)); Assert.assertTrue(result >= -1 && result < 0); result = Erf.erfc(i); Assert.assertFalse(Double.isNaN(result)); Assert.assertTrue(result >= 0 && result < 1); result = Erf.erfc(-i); Assert.assertFalse(Double.isNaN(result)); Assert.assertTrue(result >= 1 && result <= 2); } Assert.assertEquals(-1, Erf.erf(Double.NEGATIVE_INFINITY), 0); Assert.assertEquals(1, Erf.erf(Double.POSITIVE_INFINITY), 0); Assert.assertEquals(2, Erf.erfc(Double.NEGATIVE_INFINITY), 0); Assert.assertEquals(0, Erf.erfc(Double.POSITIVE_INFINITY), 0); } /** * Compare Erf.erf against reference values computed using GCC 4.2.1 (Apple OSX packaged version) * erfl (extended precision erf). */ @Test public void testErfGnu() { final double tol = 1E-15; final double[] gnuValues = new double[] {-1, -1, -1, -1, -1, -1, -1, -1, -0.99999999999999997848, -0.99999999999999264217, -0.99999999999846254017, -0.99999999980338395581, -0.99999998458274209971, -0.9999992569016276586, -0.99997790950300141459, -0.99959304798255504108, -0.99532226501895273415, -0.96610514647531072711, -0.84270079294971486948, -0.52049987781304653809, 0, 0.52049987781304653809, 0.84270079294971486948, 0.96610514647531072711, 0.99532226501895273415, 0.99959304798255504108, 0.99997790950300141459, 0.9999992569016276586, 0.99999998458274209971, 0.99999999980338395581, 0.99999999999846254017, 0.99999999999999264217, 0.99999999999999997848, 1, 1, 1, 1, 1, 1, 1, 1}; double x = -10d; for (int i = 0; i < 41; i++) { Assert.assertEquals(gnuValues[i], Erf.erf(x), tol); x += 0.5d; } } /** * Compare Erf.erfc against reference values computed using GCC 4.2.1 (Apple OSX packaged version) * erfcl (extended precision erfc). */ @Test public void testErfcGnu() { final double tol = 1E-15; final double[] gnuValues = new double[] { 2, 2, 2, 2, 2, 2, 2, 2, 1.9999999999999999785, 1.9999999999999926422, 1.9999999999984625402, 1.9999999998033839558, 1.9999999845827420998, 1.9999992569016276586, 1.9999779095030014146, 1.9995930479825550411, 1.9953222650189527342, 1.9661051464753107271, 1.8427007929497148695, 1.5204998778130465381, 1, 0.47950012218695346194, 0.15729920705028513051, 0.033894853524689272893, 0.0046777349810472658333, 0.00040695201744495893941, 2.2090496998585441366E-05, 7.4309837234141274516E-07, 1.5417257900280018858E-08, 1.966160441542887477E-10, 1.5374597944280348501E-12, 7.3578479179743980661E-15, 2.1519736712498913103E-17, 3.8421483271206474691E-20, 4.1838256077794144006E-23, 2.7766493860305691016E-26, 1.1224297172982927079E-29, 2.7623240713337714448E-33, 4.1370317465138102353E-37, 3.7692144856548799402E-41, 2.0884875837625447567E-45}; double x = -10d; for (int i = 0; i < 41; i++) { Assert.assertEquals(gnuValues[i], Erf.erfc(x), tol); x += 0.5d; } } /** * Tests erfc against reference data computed using Maple reported in Marsaglia, G,, * "Evaluating the Normal Distribution," Journal of Statistical Software, July, 2004. * http//www.jstatsoft.org/v11/a05/paper */ @Test public void testErfcMaple() { double[][] ref = new double[][] {{0.1, 4.60172162722971e-01}, {1.2, 1.15069670221708e-01}, {2.3, 1.07241100216758e-02}, {3.4, 3.36929265676881e-04}, {4.5, 3.39767312473006e-06}, {5.6, 1.07175902583109e-08}, {6.7, 1.04209769879652e-11}, {7.8, 3.09535877195870e-15}, {8.9, 2.79233437493966e-19}, {10.0, 7.61985302416053e-24}, {11.1, 6.27219439321703e-29}, {12.2, 1.55411978638959e-34}, {13.3, 1.15734162836904e-40}, {14.4, 2.58717592540226e-47}, {15.5, 1.73446079179387e-54}, {16.6, 3.48454651995041e-62} }; for (int i = 0; i < 15; i++) { final double result = 0.5*Erf.erfc(ref[i][0]/Math.sqrt(2)); Assert.assertEquals(ref[i][1], result, 1E-15); TestUtils.assertRelativelyEquals(ref[i][1], result, 1E-13); } } /** * Test the implementation of Erf.erf(double, double) for consistency with results * obtained from Erf.erf(double) and Erf.erfc(double). */ @Test public void testTwoArgumentErf() { double[] xi = new double[]{-2.0, -1.0, -0.9, -0.1, 0.0, 0.1, 0.9, 1.0, 2.0}; for(double x1 : xi) { for(double x2 : xi) { double a = Erf.erf(x1, x2); double b = Erf.erf(x2) - Erf.erf(x1); double c = Erf.erfc(x1) - Erf.erfc(x2); Assert.assertEquals(a, b, 1E-15); Assert.assertEquals(a, c, 1E-15); } } } @Test public void testErfInvNaN() { Assert.assertTrue(Double.isNaN(Erf.erfInv(-1.001))); Assert.assertTrue(Double.isNaN(Erf.erfInv(+1.001))); } @Test public void testErfInvInfinite() { Assert.assertTrue(Double.isInfinite(Erf.erfInv(-1))); Assert.assertTrue(Erf.erfInv(-1) < 0); Assert.assertTrue(Double.isInfinite(Erf.erfInv(+1))); Assert.assertTrue(Erf.erfInv(+1) > 0); } @Test public void testErfInv() { for (double x = -5.9; x < 5.9; x += 0.01) { final double y = Erf.erf(x); final double dydx = 2 * FastMath.exp(-x * x) / FastMath.sqrt(FastMath.PI); Assert.assertEquals(x, Erf.erfInv(y), 1.0e-15 / dydx); } } @Test public void testErfcInvNaN() { Assert.assertTrue(Double.isNaN(Erf.erfcInv(-0.001))); Assert.assertTrue(Double.isNaN(Erf.erfcInv(+2.001))); } @Test public void testErfcInvInfinite() { Assert.assertTrue(Double.isInfinite(Erf.erfcInv(-0))); Assert.assertTrue(Erf.erfcInv( 0) > 0); Assert.assertTrue(Double.isInfinite(Erf.erfcInv(+2))); Assert.assertTrue(Erf.erfcInv(+2) < 0); } @Test public void testErfcInv() { for (double x = -5.85; x < 5.9; x += 0.01) { final double y = Erf.erfc(x); final double dydxAbs = 2 * FastMath.exp(-x * x) / FastMath.sqrt(FastMath.PI); Assert.assertEquals(x, Erf.erfcInv(y), 1.0e-15 / dydxAbs); } } }
[ { "be_test_class_file": "org/apache/commons/math3/special/Erf.java", "be_test_class_name": "org.apache.commons.math3.special.Erf", "be_test_function_name": "erfc", "be_test_function_signature": "(D)D", "line_numbers": [ "98", "99", "101", "102" ], "method_line_rate": 0.75 } ]
public class ErfTest
@Test public void testErfcMaple() { double[][] ref = new double[][] {{0.1, 4.60172162722971e-01}, {1.2, 1.15069670221708e-01}, {2.3, 1.07241100216758e-02}, {3.4, 3.36929265676881e-04}, {4.5, 3.39767312473006e-06}, {5.6, 1.07175902583109e-08}, {6.7, 1.04209769879652e-11}, {7.8, 3.09535877195870e-15}, {8.9, 2.79233437493966e-19}, {10.0, 7.61985302416053e-24}, {11.1, 6.27219439321703e-29}, {12.2, 1.55411978638959e-34}, {13.3, 1.15734162836904e-40}, {14.4, 2.58717592540226e-47}, {15.5, 1.73446079179387e-54}, {16.6, 3.48454651995041e-62} }; for (int i = 0; i < 15; i++) { final double result = 0.5*Erf.erfc(ref[i][0]/Math.sqrt(2)); Assert.assertEquals(ref[i][1], result, 1E-15); TestUtils.assertRelativelyEquals(ref[i][1], result, 1E-13); } }
// // Abstract Java Tested Class // package org.apache.commons.math3.special; // // import org.apache.commons.math3.util.FastMath; // // // // public class Erf { // private static final double X_CRIT = 0.4769362762044697; // // private Erf(); // public static double erf(double x); // public static double erfc(double x); // public static double erf(double x1, double x2); // public static double erfInv(final double x); // public static double erfcInv(final double x); // } // // // Abstract Java Test Class // package org.apache.commons.math3.special; // // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.util.FastMath; // import org.junit.Test; // import org.junit.Assert; // // // // public class ErfTest { // // // @Test // public void testErf0(); // @Test // public void testErf1960(); // @Test // public void testErf2576(); // @Test // public void testErf2807(); // @Test // public void testErf3291(); // @Test // public void testLargeValues(); // @Test // public void testErfGnu(); // @Test // public void testErfcGnu(); // @Test // public void testErfcMaple(); // @Test // public void testTwoArgumentErf(); // @Test // public void testErfInvNaN(); // @Test // public void testErfInvInfinite(); // @Test // public void testErfInv(); // @Test // public void testErfcInvNaN(); // @Test // public void testErfcInvInfinite(); // @Test // public void testErfcInv(); // } // You are a professional Java test case writer, please create a test case named `testErfcMaple` for the `Erf` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests erfc against reference data computed using Maple reported in Marsaglia, G,, * "Evaluating the Normal Distribution," Journal of Statistical Software, July, 2004. * http//www.jstatsoft.org/v11/a05/paper */
src/test/java/org/apache/commons/math3/special/ErfTest.java
package org.apache.commons.math3.special; import org.apache.commons.math3.util.FastMath;
private Erf(); public static double erf(double x); public static double erfc(double x); public static double erf(double x1, double x2); public static double erfInv(final double x); public static double erfcInv(final double x);
196
testErfcMaple
```java // Abstract Java Tested Class package org.apache.commons.math3.special; import org.apache.commons.math3.util.FastMath; public class Erf { private static final double X_CRIT = 0.4769362762044697; private Erf(); public static double erf(double x); public static double erfc(double x); public static double erf(double x1, double x2); public static double erfInv(final double x); public static double erfcInv(final double x); } // Abstract Java Test Class package org.apache.commons.math3.special; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert; public class ErfTest { @Test public void testErf0(); @Test public void testErf1960(); @Test public void testErf2576(); @Test public void testErf2807(); @Test public void testErf3291(); @Test public void testLargeValues(); @Test public void testErfGnu(); @Test public void testErfcGnu(); @Test public void testErfcMaple(); @Test public void testTwoArgumentErf(); @Test public void testErfInvNaN(); @Test public void testErfInvInfinite(); @Test public void testErfInv(); @Test public void testErfcInvNaN(); @Test public void testErfcInvInfinite(); @Test public void testErfcInv(); } ``` You are a professional Java test case writer, please create a test case named `testErfcMaple` for the `Erf` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests erfc against reference data computed using Maple reported in Marsaglia, G,, * "Evaluating the Normal Distribution," Journal of Statistical Software, July, 2004. * http//www.jstatsoft.org/v11/a05/paper */
171
// // Abstract Java Tested Class // package org.apache.commons.math3.special; // // import org.apache.commons.math3.util.FastMath; // // // // public class Erf { // private static final double X_CRIT = 0.4769362762044697; // // private Erf(); // public static double erf(double x); // public static double erfc(double x); // public static double erf(double x1, double x2); // public static double erfInv(final double x); // public static double erfcInv(final double x); // } // // // Abstract Java Test Class // package org.apache.commons.math3.special; // // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.util.FastMath; // import org.junit.Test; // import org.junit.Assert; // // // // public class ErfTest { // // // @Test // public void testErf0(); // @Test // public void testErf1960(); // @Test // public void testErf2576(); // @Test // public void testErf2807(); // @Test // public void testErf3291(); // @Test // public void testLargeValues(); // @Test // public void testErfGnu(); // @Test // public void testErfcGnu(); // @Test // public void testErfcMaple(); // @Test // public void testTwoArgumentErf(); // @Test // public void testErfInvNaN(); // @Test // public void testErfInvInfinite(); // @Test // public void testErfInv(); // @Test // public void testErfcInvNaN(); // @Test // public void testErfcInvInfinite(); // @Test // public void testErfcInv(); // } // You are a professional Java test case writer, please create a test case named `testErfcMaple` for the `Erf` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests erfc against reference data computed using Maple reported in Marsaglia, G,, * "Evaluating the Normal Distribution," Journal of Statistical Software, July, 2004. * http//www.jstatsoft.org/v11/a05/paper */ @Test public void testErfcMaple() {
/** * Tests erfc against reference data computed using Maple reported in Marsaglia, G,, * "Evaluating the Normal Distribution," Journal of Statistical Software, July, 2004. * http//www.jstatsoft.org/v11/a05/paper */
1
org.apache.commons.math3.special.Erf
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.math3.special; import org.apache.commons.math3.util.FastMath; public class Erf { private static final double X_CRIT = 0.4769362762044697; private Erf(); public static double erf(double x); public static double erfc(double x); public static double erf(double x1, double x2); public static double erfInv(final double x); public static double erfcInv(final double x); } // Abstract Java Test Class package org.apache.commons.math3.special; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert; public class ErfTest { @Test public void testErf0(); @Test public void testErf1960(); @Test public void testErf2576(); @Test public void testErf2807(); @Test public void testErf3291(); @Test public void testLargeValues(); @Test public void testErfGnu(); @Test public void testErfcGnu(); @Test public void testErfcMaple(); @Test public void testTwoArgumentErf(); @Test public void testErfInvNaN(); @Test public void testErfInvInfinite(); @Test public void testErfInv(); @Test public void testErfcInvNaN(); @Test public void testErfcInvInfinite(); @Test public void testErfcInv(); } ``` You are a professional Java test case writer, please create a test case named `testErfcMaple` for the `Erf` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests erfc against reference data computed using Maple reported in Marsaglia, G,, * "Evaluating the Normal Distribution," Journal of Statistical Software, July, 2004. * http//www.jstatsoft.org/v11/a05/paper */ @Test public void testErfcMaple() { ```
public class Erf
package org.apache.commons.math3.special; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert;
@Test public void testErf0(); @Test public void testErf1960(); @Test public void testErf2576(); @Test public void testErf2807(); @Test public void testErf3291(); @Test public void testLargeValues(); @Test public void testErfGnu(); @Test public void testErfcGnu(); @Test public void testErfcMaple(); @Test public void testTwoArgumentErf(); @Test public void testErfInvNaN(); @Test public void testErfInvInfinite(); @Test public void testErfInv(); @Test public void testErfcInvNaN(); @Test public void testErfcInvInfinite(); @Test public void testErfcInv();
1d5422bec6d9d04b2264f34d1a8e9c728e957b1a1dddb8107e74fc70ac540ec1
[ "org.apache.commons.math3.special.ErfTest::testErfcMaple" ]
private static final double X_CRIT = 0.4769362762044697;
@Test public void testErfcMaple()
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.special; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert; /** * @version $Id$ */ public class ErfTest { @Test public void testErf0() { double actual = Erf.erf(0.0); double expected = 0.0; Assert.assertEquals(expected, actual, 1.0e-15); Assert.assertEquals(1 - expected, Erf.erfc(0.0), 1.0e-15); } @Test public void testErf1960() { double x = 1.960 / FastMath.sqrt(2.0); double actual = Erf.erf(x); double expected = 0.95; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(x), 1.0e-15); actual = Erf.erf(-x); expected = -expected; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(-x), 1.0e-15); } @Test public void testErf2576() { double x = 2.576 / FastMath.sqrt(2.0); double actual = Erf.erf(x); double expected = 0.99; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(x), 1e-15); actual = Erf.erf(-x); expected = -expected; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(-x), 1.0e-15); } @Test public void testErf2807() { double x = 2.807 / FastMath.sqrt(2.0); double actual = Erf.erf(x); double expected = 0.995; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(x), 1.0e-15); actual = Erf.erf(-x); expected = -expected; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(-x), 1.0e-15); } @Test public void testErf3291() { double x = 3.291 / FastMath.sqrt(2.0); double actual = Erf.erf(x); double expected = 0.999; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - expected, Erf.erfc(x), 1.0e-5); actual = Erf.erf(-x); expected = -expected; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - expected, Erf.erfc(-x), 1.0e-5); } /** * MATH-301, MATH-456 */ @Test public void testLargeValues() { for (int i = 1; i < 200; i*=10) { double result = Erf.erf(i); Assert.assertFalse(Double.isNaN(result)); Assert.assertTrue(result > 0 && result <= 1); result = Erf.erf(-i); Assert.assertFalse(Double.isNaN(result)); Assert.assertTrue(result >= -1 && result < 0); result = Erf.erfc(i); Assert.assertFalse(Double.isNaN(result)); Assert.assertTrue(result >= 0 && result < 1); result = Erf.erfc(-i); Assert.assertFalse(Double.isNaN(result)); Assert.assertTrue(result >= 1 && result <= 2); } Assert.assertEquals(-1, Erf.erf(Double.NEGATIVE_INFINITY), 0); Assert.assertEquals(1, Erf.erf(Double.POSITIVE_INFINITY), 0); Assert.assertEquals(2, Erf.erfc(Double.NEGATIVE_INFINITY), 0); Assert.assertEquals(0, Erf.erfc(Double.POSITIVE_INFINITY), 0); } /** * Compare Erf.erf against reference values computed using GCC 4.2.1 (Apple OSX packaged version) * erfl (extended precision erf). */ @Test public void testErfGnu() { final double tol = 1E-15; final double[] gnuValues = new double[] {-1, -1, -1, -1, -1, -1, -1, -1, -0.99999999999999997848, -0.99999999999999264217, -0.99999999999846254017, -0.99999999980338395581, -0.99999998458274209971, -0.9999992569016276586, -0.99997790950300141459, -0.99959304798255504108, -0.99532226501895273415, -0.96610514647531072711, -0.84270079294971486948, -0.52049987781304653809, 0, 0.52049987781304653809, 0.84270079294971486948, 0.96610514647531072711, 0.99532226501895273415, 0.99959304798255504108, 0.99997790950300141459, 0.9999992569016276586, 0.99999998458274209971, 0.99999999980338395581, 0.99999999999846254017, 0.99999999999999264217, 0.99999999999999997848, 1, 1, 1, 1, 1, 1, 1, 1}; double x = -10d; for (int i = 0; i < 41; i++) { Assert.assertEquals(gnuValues[i], Erf.erf(x), tol); x += 0.5d; } } /** * Compare Erf.erfc against reference values computed using GCC 4.2.1 (Apple OSX packaged version) * erfcl (extended precision erfc). */ @Test public void testErfcGnu() { final double tol = 1E-15; final double[] gnuValues = new double[] { 2, 2, 2, 2, 2, 2, 2, 2, 1.9999999999999999785, 1.9999999999999926422, 1.9999999999984625402, 1.9999999998033839558, 1.9999999845827420998, 1.9999992569016276586, 1.9999779095030014146, 1.9995930479825550411, 1.9953222650189527342, 1.9661051464753107271, 1.8427007929497148695, 1.5204998778130465381, 1, 0.47950012218695346194, 0.15729920705028513051, 0.033894853524689272893, 0.0046777349810472658333, 0.00040695201744495893941, 2.2090496998585441366E-05, 7.4309837234141274516E-07, 1.5417257900280018858E-08, 1.966160441542887477E-10, 1.5374597944280348501E-12, 7.3578479179743980661E-15, 2.1519736712498913103E-17, 3.8421483271206474691E-20, 4.1838256077794144006E-23, 2.7766493860305691016E-26, 1.1224297172982927079E-29, 2.7623240713337714448E-33, 4.1370317465138102353E-37, 3.7692144856548799402E-41, 2.0884875837625447567E-45}; double x = -10d; for (int i = 0; i < 41; i++) { Assert.assertEquals(gnuValues[i], Erf.erfc(x), tol); x += 0.5d; } } /** * Tests erfc against reference data computed using Maple reported in Marsaglia, G,, * "Evaluating the Normal Distribution," Journal of Statistical Software, July, 2004. * http//www.jstatsoft.org/v11/a05/paper */ @Test public void testErfcMaple() { double[][] ref = new double[][] {{0.1, 4.60172162722971e-01}, {1.2, 1.15069670221708e-01}, {2.3, 1.07241100216758e-02}, {3.4, 3.36929265676881e-04}, {4.5, 3.39767312473006e-06}, {5.6, 1.07175902583109e-08}, {6.7, 1.04209769879652e-11}, {7.8, 3.09535877195870e-15}, {8.9, 2.79233437493966e-19}, {10.0, 7.61985302416053e-24}, {11.1, 6.27219439321703e-29}, {12.2, 1.55411978638959e-34}, {13.3, 1.15734162836904e-40}, {14.4, 2.58717592540226e-47}, {15.5, 1.73446079179387e-54}, {16.6, 3.48454651995041e-62} }; for (int i = 0; i < 15; i++) { final double result = 0.5*Erf.erfc(ref[i][0]/Math.sqrt(2)); Assert.assertEquals(ref[i][1], result, 1E-15); TestUtils.assertRelativelyEquals(ref[i][1], result, 1E-13); } } /** * Test the implementation of Erf.erf(double, double) for consistency with results * obtained from Erf.erf(double) and Erf.erfc(double). */ @Test public void testTwoArgumentErf() { double[] xi = new double[]{-2.0, -1.0, -0.9, -0.1, 0.0, 0.1, 0.9, 1.0, 2.0}; for(double x1 : xi) { for(double x2 : xi) { double a = Erf.erf(x1, x2); double b = Erf.erf(x2) - Erf.erf(x1); double c = Erf.erfc(x1) - Erf.erfc(x2); Assert.assertEquals(a, b, 1E-15); Assert.assertEquals(a, c, 1E-15); } } } @Test public void testErfInvNaN() { Assert.assertTrue(Double.isNaN(Erf.erfInv(-1.001))); Assert.assertTrue(Double.isNaN(Erf.erfInv(+1.001))); } @Test public void testErfInvInfinite() { Assert.assertTrue(Double.isInfinite(Erf.erfInv(-1))); Assert.assertTrue(Erf.erfInv(-1) < 0); Assert.assertTrue(Double.isInfinite(Erf.erfInv(+1))); Assert.assertTrue(Erf.erfInv(+1) > 0); } @Test public void testErfInv() { for (double x = -5.9; x < 5.9; x += 0.01) { final double y = Erf.erf(x); final double dydx = 2 * FastMath.exp(-x * x) / FastMath.sqrt(FastMath.PI); Assert.assertEquals(x, Erf.erfInv(y), 1.0e-15 / dydx); } } @Test public void testErfcInvNaN() { Assert.assertTrue(Double.isNaN(Erf.erfcInv(-0.001))); Assert.assertTrue(Double.isNaN(Erf.erfcInv(+2.001))); } @Test public void testErfcInvInfinite() { Assert.assertTrue(Double.isInfinite(Erf.erfcInv(-0))); Assert.assertTrue(Erf.erfcInv( 0) > 0); Assert.assertTrue(Double.isInfinite(Erf.erfcInv(+2))); Assert.assertTrue(Erf.erfcInv(+2) < 0); } @Test public void testErfcInv() { for (double x = -5.85; x < 5.9; x += 0.01) { final double y = Erf.erfc(x); final double dydxAbs = 2 * FastMath.exp(-x * x) / FastMath.sqrt(FastMath.PI); Assert.assertEquals(x, Erf.erfcInv(y), 1.0e-15 / dydxAbs); } } }
[ { "be_test_class_file": "org/apache/commons/math3/special/Erf.java", "be_test_class_name": "org.apache.commons.math3.special.Erf", "be_test_function_name": "erfc", "be_test_function_signature": "(D)D", "line_numbers": [ "98", "99", "101", "102" ], "method_line_rate": 0.75 } ]
public class DateAxisTests extends TestCase
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()); }
// 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 `testPreviousStandardDateDayB` 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 7 days (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);
767
testPreviousStandardDateDayB
```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 `testPreviousStandardDateDayB` 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 7 days (just for the sake of having a multiple). */
700
// 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 `testPreviousStandardDateDayB` 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 7 days (just for the sake of having a multiple). */ public void testPreviousStandardDateDayB() {
/** * A basic check for the testPreviousStandardDate() method when the * tick unit is 7 days (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 `testPreviousStandardDateDayB` 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 7 days (just for the sake of having a multiple). */ public void testPreviousStandardDateDayB() { ```
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);
1e3fd2d1040fd49c89176743f3aeb7abb35748a04d47a78ef7e81d6ceaa6efe4
[ "org.jfree.chart.axis.junit.DateAxisTests::testPreviousStandardDateDayB" ]
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 testPreviousStandardDateDayB()
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.23387096774193547 }, { "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 CheckPathsBetweenNodesTest extends TestCase
public void testCycles2() { DiGraph<String, String> g = LinkedDirectedGraph.create(); g.createDirectedGraphNode("a"); g.createDirectedGraphNode("b"); g.createDirectedGraphNode("c"); g.createDirectedGraphNode("d"); g.connect("a", "-", "b"); g.connect("b", "-", "c"); g.connect("c", "-", "b"); g.connect("b", "-", "d"); assertGood(createTest(g, "a", "d", Predicates.equalTo("a"), ALL_EDGE)); assertBad(createTest(g, "a", "d", Predicates.equalTo("z"), ALL_EDGE)); }
// // Abstract Java Tested Class // package com.google.javascript.jscomp; // // import com.google.common.base.Predicate; // import com.google.javascript.jscomp.graph.Annotation; // import com.google.javascript.jscomp.graph.DiGraph; // import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge; // import com.google.javascript.jscomp.graph.DiGraph.DiGraphNode; // // // // class CheckPathsBetweenNodes<N, E> { // private final Predicate<N> nodePredicate; // private final Predicate<DiGraphEdge<N, E>> edgePredicate; // private final boolean inclusive; // private static final Annotation BACK_EDGE = new Annotation() {}; // private static final Annotation VISITED_EDGE = new Annotation() {}; // private static final Annotation WHITE = null; // private static final Annotation GRAY = new Annotation() {}; // private static final Annotation BLACK = new Annotation() {}; // private final DiGraph<N, E> graph; // private final DiGraphNode<N, E> start; // private final DiGraphNode<N, E> end; // // CheckPathsBetweenNodes(DiGraph<N, E> graph, DiGraphNode<N, E> a, // DiGraphNode<N, E> b, Predicate<N> nodePredicate, // Predicate<DiGraphEdge<N, E>> edgePredicate, boolean inclusive); // CheckPathsBetweenNodes(DiGraph<N, E> graph, DiGraphNode<N, E> a, // DiGraphNode<N, E> b, Predicate<N> nodePredicate, // Predicate<DiGraphEdge<N, E>> edgePredicate); // public boolean allPathsSatisfyPredicate(); // public boolean somePathsSatisfyPredicate(); // private void setUp(); // private void tearDown(); // private void discoverBackEdges(DiGraphNode<N, E> u); // private boolean ignoreEdge(DiGraphEdge<N, E> e); // private boolean checkAllPathsWithoutBackEdges(DiGraphNode<N, E> a, // DiGraphNode<N, E> b); // private boolean checkSomePathsWithoutBackEdges(DiGraphNode<N, E> a, // DiGraphNode<N, E> b); // } // // // Abstract Java Test Class // package com.google.javascript.jscomp; // // import com.google.common.base.Predicate; // import com.google.common.base.Predicates; // import com.google.javascript.jscomp.graph.LinkedDirectedGraph; // import com.google.javascript.jscomp.graph.DiGraph; // import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge; // import junit.framework.TestCase; // // // // public class CheckPathsBetweenNodesTest extends TestCase { // private static final Predicate<String> FALSE = Predicates.alwaysFalse(); // private static final Predicate<DiGraphEdge<String, String>> ALL_EDGE = // Predicates.alwaysTrue(); // private static final Predicate<DiGraphEdge<String, String>> NO_EDGE = // Predicates.alwaysFalse(); // // public void testSimple(); // public void testSomeValidPaths(); // public void testManyValidPaths(); // public void testCycles1(); // public void testCycles2(); // public void testCycles3(); // public void testSomePath1(); // public void testSomePath2(); // public void testSomePathRevisiting(); // public void testNonInclusive(); // private static <N, E> void assertGood(CheckPathsBetweenNodes<N, E> test); // private static <N, E> void assertBad(CheckPathsBetweenNodes<N, E> test); // private static CheckPathsBetweenNodes<String, String> createTest( // DiGraph<String, String> graph, // String entry, // String exit, // Predicate<String> nodePredicate, // Predicate<DiGraphEdge<String, String>> edgePredicate); // private static CheckPathsBetweenNodes<String, String> // createNonInclusiveTest( // DiGraph<String, String> graph, // String entry, // String exit, // Predicate<String> nodePredicate, // Predicate<DiGraphEdge<String, String>> edgePredicate); // private static Predicate<DiGraphEdge<String, String>> // edgeIs(final Object val); // PrefixPredicate(String prefix); // @Override // public boolean apply(String input); // private CountingPredicate(Predicate<T> delegate); // @Override // public boolean apply(T input); // @Override // public boolean apply(DiGraphEdge<String, String> input); // } // You are a professional Java test case writer, please create a test case named `testCycles2` for the `CheckPathsBetweenNodes` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests another graph with cycles. The topology of this graph was inspired * by a control flow graph that was being incorrectly analyzed by an early * version of CheckPathsBetweenNodes. */
test/com/google/javascript/jscomp/CheckPathsBetweenNodesTest.java
package com.google.javascript.jscomp; import com.google.common.base.Predicate; import com.google.javascript.jscomp.graph.Annotation; import com.google.javascript.jscomp.graph.DiGraph; import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge; import com.google.javascript.jscomp.graph.DiGraph.DiGraphNode;
CheckPathsBetweenNodes(DiGraph<N, E> graph, DiGraphNode<N, E> a, DiGraphNode<N, E> b, Predicate<N> nodePredicate, Predicate<DiGraphEdge<N, E>> edgePredicate, boolean inclusive); CheckPathsBetweenNodes(DiGraph<N, E> graph, DiGraphNode<N, E> a, DiGraphNode<N, E> b, Predicate<N> nodePredicate, Predicate<DiGraphEdge<N, E>> edgePredicate); public boolean allPathsSatisfyPredicate(); public boolean somePathsSatisfyPredicate(); private void setUp(); private void tearDown(); private void discoverBackEdges(DiGraphNode<N, E> u); private boolean ignoreEdge(DiGraphEdge<N, E> e); private boolean checkAllPathsWithoutBackEdges(DiGraphNode<N, E> a, DiGraphNode<N, E> b); private boolean checkSomePathsWithoutBackEdges(DiGraphNode<N, E> a, DiGraphNode<N, E> b);
168
testCycles2
```java // Abstract Java Tested Class package com.google.javascript.jscomp; import com.google.common.base.Predicate; import com.google.javascript.jscomp.graph.Annotation; import com.google.javascript.jscomp.graph.DiGraph; import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge; import com.google.javascript.jscomp.graph.DiGraph.DiGraphNode; class CheckPathsBetweenNodes<N, E> { private final Predicate<N> nodePredicate; private final Predicate<DiGraphEdge<N, E>> edgePredicate; private final boolean inclusive; private static final Annotation BACK_EDGE = new Annotation() {}; private static final Annotation VISITED_EDGE = new Annotation() {}; private static final Annotation WHITE = null; private static final Annotation GRAY = new Annotation() {}; private static final Annotation BLACK = new Annotation() {}; private final DiGraph<N, E> graph; private final DiGraphNode<N, E> start; private final DiGraphNode<N, E> end; CheckPathsBetweenNodes(DiGraph<N, E> graph, DiGraphNode<N, E> a, DiGraphNode<N, E> b, Predicate<N> nodePredicate, Predicate<DiGraphEdge<N, E>> edgePredicate, boolean inclusive); CheckPathsBetweenNodes(DiGraph<N, E> graph, DiGraphNode<N, E> a, DiGraphNode<N, E> b, Predicate<N> nodePredicate, Predicate<DiGraphEdge<N, E>> edgePredicate); public boolean allPathsSatisfyPredicate(); public boolean somePathsSatisfyPredicate(); private void setUp(); private void tearDown(); private void discoverBackEdges(DiGraphNode<N, E> u); private boolean ignoreEdge(DiGraphEdge<N, E> e); private boolean checkAllPathsWithoutBackEdges(DiGraphNode<N, E> a, DiGraphNode<N, E> b); private boolean checkSomePathsWithoutBackEdges(DiGraphNode<N, E> a, DiGraphNode<N, E> b); } // Abstract Java Test Class package com.google.javascript.jscomp; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.javascript.jscomp.graph.LinkedDirectedGraph; import com.google.javascript.jscomp.graph.DiGraph; import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge; import junit.framework.TestCase; public class CheckPathsBetweenNodesTest extends TestCase { private static final Predicate<String> FALSE = Predicates.alwaysFalse(); private static final Predicate<DiGraphEdge<String, String>> ALL_EDGE = Predicates.alwaysTrue(); private static final Predicate<DiGraphEdge<String, String>> NO_EDGE = Predicates.alwaysFalse(); public void testSimple(); public void testSomeValidPaths(); public void testManyValidPaths(); public void testCycles1(); public void testCycles2(); public void testCycles3(); public void testSomePath1(); public void testSomePath2(); public void testSomePathRevisiting(); public void testNonInclusive(); private static <N, E> void assertGood(CheckPathsBetweenNodes<N, E> test); private static <N, E> void assertBad(CheckPathsBetweenNodes<N, E> test); private static CheckPathsBetweenNodes<String, String> createTest( DiGraph<String, String> graph, String entry, String exit, Predicate<String> nodePredicate, Predicate<DiGraphEdge<String, String>> edgePredicate); private static CheckPathsBetweenNodes<String, String> createNonInclusiveTest( DiGraph<String, String> graph, String entry, String exit, Predicate<String> nodePredicate, Predicate<DiGraphEdge<String, String>> edgePredicate); private static Predicate<DiGraphEdge<String, String>> edgeIs(final Object val); PrefixPredicate(String prefix); @Override public boolean apply(String input); private CountingPredicate(Predicate<T> delegate); @Override public boolean apply(T input); @Override public boolean apply(DiGraphEdge<String, String> input); } ``` You are a professional Java test case writer, please create a test case named `testCycles2` for the `CheckPathsBetweenNodes` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests another graph with cycles. The topology of this graph was inspired * by a control flow graph that was being incorrectly analyzed by an early * version of CheckPathsBetweenNodes. */
154
// // Abstract Java Tested Class // package com.google.javascript.jscomp; // // import com.google.common.base.Predicate; // import com.google.javascript.jscomp.graph.Annotation; // import com.google.javascript.jscomp.graph.DiGraph; // import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge; // import com.google.javascript.jscomp.graph.DiGraph.DiGraphNode; // // // // class CheckPathsBetweenNodes<N, E> { // private final Predicate<N> nodePredicate; // private final Predicate<DiGraphEdge<N, E>> edgePredicate; // private final boolean inclusive; // private static final Annotation BACK_EDGE = new Annotation() {}; // private static final Annotation VISITED_EDGE = new Annotation() {}; // private static final Annotation WHITE = null; // private static final Annotation GRAY = new Annotation() {}; // private static final Annotation BLACK = new Annotation() {}; // private final DiGraph<N, E> graph; // private final DiGraphNode<N, E> start; // private final DiGraphNode<N, E> end; // // CheckPathsBetweenNodes(DiGraph<N, E> graph, DiGraphNode<N, E> a, // DiGraphNode<N, E> b, Predicate<N> nodePredicate, // Predicate<DiGraphEdge<N, E>> edgePredicate, boolean inclusive); // CheckPathsBetweenNodes(DiGraph<N, E> graph, DiGraphNode<N, E> a, // DiGraphNode<N, E> b, Predicate<N> nodePredicate, // Predicate<DiGraphEdge<N, E>> edgePredicate); // public boolean allPathsSatisfyPredicate(); // public boolean somePathsSatisfyPredicate(); // private void setUp(); // private void tearDown(); // private void discoverBackEdges(DiGraphNode<N, E> u); // private boolean ignoreEdge(DiGraphEdge<N, E> e); // private boolean checkAllPathsWithoutBackEdges(DiGraphNode<N, E> a, // DiGraphNode<N, E> b); // private boolean checkSomePathsWithoutBackEdges(DiGraphNode<N, E> a, // DiGraphNode<N, E> b); // } // // // Abstract Java Test Class // package com.google.javascript.jscomp; // // import com.google.common.base.Predicate; // import com.google.common.base.Predicates; // import com.google.javascript.jscomp.graph.LinkedDirectedGraph; // import com.google.javascript.jscomp.graph.DiGraph; // import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge; // import junit.framework.TestCase; // // // // public class CheckPathsBetweenNodesTest extends TestCase { // private static final Predicate<String> FALSE = Predicates.alwaysFalse(); // private static final Predicate<DiGraphEdge<String, String>> ALL_EDGE = // Predicates.alwaysTrue(); // private static final Predicate<DiGraphEdge<String, String>> NO_EDGE = // Predicates.alwaysFalse(); // // public void testSimple(); // public void testSomeValidPaths(); // public void testManyValidPaths(); // public void testCycles1(); // public void testCycles2(); // public void testCycles3(); // public void testSomePath1(); // public void testSomePath2(); // public void testSomePathRevisiting(); // public void testNonInclusive(); // private static <N, E> void assertGood(CheckPathsBetweenNodes<N, E> test); // private static <N, E> void assertBad(CheckPathsBetweenNodes<N, E> test); // private static CheckPathsBetweenNodes<String, String> createTest( // DiGraph<String, String> graph, // String entry, // String exit, // Predicate<String> nodePredicate, // Predicate<DiGraphEdge<String, String>> edgePredicate); // private static CheckPathsBetweenNodes<String, String> // createNonInclusiveTest( // DiGraph<String, String> graph, // String entry, // String exit, // Predicate<String> nodePredicate, // Predicate<DiGraphEdge<String, String>> edgePredicate); // private static Predicate<DiGraphEdge<String, String>> // edgeIs(final Object val); // PrefixPredicate(String prefix); // @Override // public boolean apply(String input); // private CountingPredicate(Predicate<T> delegate); // @Override // public boolean apply(T input); // @Override // public boolean apply(DiGraphEdge<String, String> input); // } // You are a professional Java test case writer, please create a test case named `testCycles2` for the `CheckPathsBetweenNodes` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests another graph with cycles. The topology of this graph was inspired * by a control flow graph that was being incorrectly analyzed by an early * version of CheckPathsBetweenNodes. */ public void testCycles2() {
/** * Tests another graph with cycles. The topology of this graph was inspired * by a control flow graph that was being incorrectly analyzed by an early * version of CheckPathsBetweenNodes. */
107
com.google.javascript.jscomp.CheckPathsBetweenNodes
test
```java // Abstract Java Tested Class package com.google.javascript.jscomp; import com.google.common.base.Predicate; import com.google.javascript.jscomp.graph.Annotation; import com.google.javascript.jscomp.graph.DiGraph; import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge; import com.google.javascript.jscomp.graph.DiGraph.DiGraphNode; class CheckPathsBetweenNodes<N, E> { private final Predicate<N> nodePredicate; private final Predicate<DiGraphEdge<N, E>> edgePredicate; private final boolean inclusive; private static final Annotation BACK_EDGE = new Annotation() {}; private static final Annotation VISITED_EDGE = new Annotation() {}; private static final Annotation WHITE = null; private static final Annotation GRAY = new Annotation() {}; private static final Annotation BLACK = new Annotation() {}; private final DiGraph<N, E> graph; private final DiGraphNode<N, E> start; private final DiGraphNode<N, E> end; CheckPathsBetweenNodes(DiGraph<N, E> graph, DiGraphNode<N, E> a, DiGraphNode<N, E> b, Predicate<N> nodePredicate, Predicate<DiGraphEdge<N, E>> edgePredicate, boolean inclusive); CheckPathsBetweenNodes(DiGraph<N, E> graph, DiGraphNode<N, E> a, DiGraphNode<N, E> b, Predicate<N> nodePredicate, Predicate<DiGraphEdge<N, E>> edgePredicate); public boolean allPathsSatisfyPredicate(); public boolean somePathsSatisfyPredicate(); private void setUp(); private void tearDown(); private void discoverBackEdges(DiGraphNode<N, E> u); private boolean ignoreEdge(DiGraphEdge<N, E> e); private boolean checkAllPathsWithoutBackEdges(DiGraphNode<N, E> a, DiGraphNode<N, E> b); private boolean checkSomePathsWithoutBackEdges(DiGraphNode<N, E> a, DiGraphNode<N, E> b); } // Abstract Java Test Class package com.google.javascript.jscomp; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.javascript.jscomp.graph.LinkedDirectedGraph; import com.google.javascript.jscomp.graph.DiGraph; import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge; import junit.framework.TestCase; public class CheckPathsBetweenNodesTest extends TestCase { private static final Predicate<String> FALSE = Predicates.alwaysFalse(); private static final Predicate<DiGraphEdge<String, String>> ALL_EDGE = Predicates.alwaysTrue(); private static final Predicate<DiGraphEdge<String, String>> NO_EDGE = Predicates.alwaysFalse(); public void testSimple(); public void testSomeValidPaths(); public void testManyValidPaths(); public void testCycles1(); public void testCycles2(); public void testCycles3(); public void testSomePath1(); public void testSomePath2(); public void testSomePathRevisiting(); public void testNonInclusive(); private static <N, E> void assertGood(CheckPathsBetweenNodes<N, E> test); private static <N, E> void assertBad(CheckPathsBetweenNodes<N, E> test); private static CheckPathsBetweenNodes<String, String> createTest( DiGraph<String, String> graph, String entry, String exit, Predicate<String> nodePredicate, Predicate<DiGraphEdge<String, String>> edgePredicate); private static CheckPathsBetweenNodes<String, String> createNonInclusiveTest( DiGraph<String, String> graph, String entry, String exit, Predicate<String> nodePredicate, Predicate<DiGraphEdge<String, String>> edgePredicate); private static Predicate<DiGraphEdge<String, String>> edgeIs(final Object val); PrefixPredicate(String prefix); @Override public boolean apply(String input); private CountingPredicate(Predicate<T> delegate); @Override public boolean apply(T input); @Override public boolean apply(DiGraphEdge<String, String> input); } ``` You are a professional Java test case writer, please create a test case named `testCycles2` for the `CheckPathsBetweenNodes` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests another graph with cycles. The topology of this graph was inspired * by a control flow graph that was being incorrectly analyzed by an early * version of CheckPathsBetweenNodes. */ public void testCycles2() { ```
class CheckPathsBetweenNodes<N, E>
package com.google.javascript.jscomp; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.javascript.jscomp.graph.LinkedDirectedGraph; import com.google.javascript.jscomp.graph.DiGraph; import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge; import junit.framework.TestCase;
public void testSimple(); public void testSomeValidPaths(); public void testManyValidPaths(); public void testCycles1(); public void testCycles2(); public void testCycles3(); public void testSomePath1(); public void testSomePath2(); public void testSomePathRevisiting(); public void testNonInclusive(); private static <N, E> void assertGood(CheckPathsBetweenNodes<N, E> test); private static <N, E> void assertBad(CheckPathsBetweenNodes<N, E> test); private static CheckPathsBetweenNodes<String, String> createTest( DiGraph<String, String> graph, String entry, String exit, Predicate<String> nodePredicate, Predicate<DiGraphEdge<String, String>> edgePredicate); private static CheckPathsBetweenNodes<String, String> createNonInclusiveTest( DiGraph<String, String> graph, String entry, String exit, Predicate<String> nodePredicate, Predicate<DiGraphEdge<String, String>> edgePredicate); private static Predicate<DiGraphEdge<String, String>> edgeIs(final Object val); PrefixPredicate(String prefix); @Override public boolean apply(String input); private CountingPredicate(Predicate<T> delegate); @Override public boolean apply(T input); @Override public boolean apply(DiGraphEdge<String, String> input);
1fb2d18fae6a0aa62d08f0ab5d8dd4ed07fe9035cc05ea0de08b092746ea6225
[ "com.google.javascript.jscomp.CheckPathsBetweenNodesTest::testCycles2" ]
private final Predicate<N> nodePredicate; private final Predicate<DiGraphEdge<N, E>> edgePredicate; private final boolean inclusive; private static final Annotation BACK_EDGE = new Annotation() {}; private static final Annotation VISITED_EDGE = new Annotation() {}; private static final Annotation WHITE = null; private static final Annotation GRAY = new Annotation() {}; private static final Annotation BLACK = new Annotation() {}; private final DiGraph<N, E> graph; private final DiGraphNode<N, E> start; private final DiGraphNode<N, E> end;
public void testCycles2()
private static final Predicate<String> FALSE = Predicates.alwaysFalse(); private static final Predicate<DiGraphEdge<String, String>> ALL_EDGE = Predicates.alwaysTrue(); private static final Predicate<DiGraphEdge<String, String>> NO_EDGE = Predicates.alwaysFalse();
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.base.Predicate; import com.google.common.base.Predicates; import com.google.javascript.jscomp.graph.LinkedDirectedGraph; import com.google.javascript.jscomp.graph.DiGraph; import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge; import junit.framework.TestCase; /** * Tests for {@link CheckPathsBetweenNodes}. * */ public class CheckPathsBetweenNodesTest extends TestCase { /** * Predicate satisfied by strings with a given prefix. */ private static class PrefixPredicate implements Predicate<String> { String prefix; PrefixPredicate(String prefix) { this.prefix = prefix; } @Override public boolean apply(String input) { return input.startsWith(prefix); } } private static final Predicate<String> FALSE = Predicates.alwaysFalse(); private static final Predicate<DiGraphEdge<String, String>> ALL_EDGE = Predicates.alwaysTrue(); private static final Predicate<DiGraphEdge<String, String>> NO_EDGE = Predicates.alwaysFalse(); /** Tests straight-line graphs. */ public void testSimple() { DiGraph<String, String> g = LinkedDirectedGraph.create(); g.createDirectedGraphNode("a"); g.createDirectedGraphNode("b"); g.createDirectedGraphNode("c"); g.createDirectedGraphNode("d"); g.connect("a", "-", "b"); g.connect("b", "-", "c"); g.connect("c", "-", "d"); g.connect("a", "x", "d"); // Simple case: the sole path from a to d has a matching node. assertGood(createTest(g, "a", "d", Predicates.equalTo("b"), edgeIs("-"))); //Test two edge cases where satisfying node is the first and last node on // the path. assertGood(createTest(g, "a", "d", Predicates.equalTo("a"), edgeIs("-"))); assertGood(createTest(g, "a", "d", Predicates.equalTo("d"), edgeIs("-"))); // Traverse no edges, so no paths. assertGood(createTest(g, "a", "d", FALSE, NO_EDGE)); // No path with matching edges contains b. assertBad(createTest(g, "a", "d", Predicates.equalTo("b"), edgeIs("x"))); } /** * Tests a graph where some paths between the nodes are valid and others * are invalid. */ public void testSomeValidPaths() { DiGraph<String, String> g = LinkedDirectedGraph.create(); g.createDirectedGraphNode("a"); g.createDirectedGraphNode("b"); g.createDirectedGraphNode("c"); g.createDirectedGraphNode("d"); g.createDirectedGraphNode("e"); g.connect("a", "1", "b"); g.connect("b", "2", "c"); g.connect("b", "3", "e"); g.connect("e", "4", "d"); g.connect("c", "5", "d"); assertBad(createTest(g, "a", "d", Predicates.equalTo("c"), ALL_EDGE)); assertBad(createTest(g, "a", "d", Predicates.equalTo("z"), ALL_EDGE)); } /** Tests a graph with many valid paths. */ public void testManyValidPaths() { DiGraph<String, String> g = LinkedDirectedGraph.create(); g.createDirectedGraphNode("a"); g.createDirectedGraphNode("b"); g.createDirectedGraphNode("c1"); g.createDirectedGraphNode("c2"); g.createDirectedGraphNode("c3"); g.createDirectedGraphNode("d"); g.connect("a", "-", "b"); g.connect("b", "-", "c1"); g.connect("b", "-", "c2"); g.connect("c2", "-", "d"); g.connect("c1", "-", "d"); g.connect("a", "-", "c3"); g.connect("c3", "-", "d"); assertGood(createTest(g, "a", "d", new PrefixPredicate("c"), ALL_EDGE)); } /** Tests a graph with some cycles. */ public void testCycles1() { DiGraph<String, String> g = LinkedDirectedGraph.create(); g.createDirectedGraphNode("a"); g.createDirectedGraphNode("b"); g.createDirectedGraphNode("c"); g.createDirectedGraphNode("d"); g.createDirectedGraphNode("e"); g.createDirectedGraphNode("f"); g.connect("a", "-", "b"); g.connect("b", "-", "c"); g.connect("c", "-", "d"); g.connect("d", "-", "e"); g.connect("e", "-", "f"); g.connect("f", "-", "b"); assertGood(createTest(g, "a", "e", Predicates.equalTo("b"), ALL_EDGE)); assertGood(createTest(g, "a", "e", Predicates.equalTo("c"), ALL_EDGE)); assertGood(createTest(g, "a", "e", Predicates.equalTo("d"), ALL_EDGE)); assertGood(createTest(g, "a", "e", Predicates.equalTo("e"), ALL_EDGE)); assertBad(createTest(g, "a", "e", Predicates.equalTo("f"), ALL_EDGE)); } /** * Tests another graph with cycles. The topology of this graph was inspired * by a control flow graph that was being incorrectly analyzed by an early * version of CheckPathsBetweenNodes. */ public void testCycles2() { DiGraph<String, String> g = LinkedDirectedGraph.create(); g.createDirectedGraphNode("a"); g.createDirectedGraphNode("b"); g.createDirectedGraphNode("c"); g.createDirectedGraphNode("d"); g.connect("a", "-", "b"); g.connect("b", "-", "c"); g.connect("c", "-", "b"); g.connect("b", "-", "d"); assertGood(createTest(g, "a", "d", Predicates.equalTo("a"), ALL_EDGE)); assertBad(createTest(g, "a", "d", Predicates.equalTo("z"), ALL_EDGE)); } /** * Tests another graph with cycles. The topology of this graph was inspired * by a control flow graph that was being incorrectly analyzed by an early * version of CheckPathsBetweenNodes. */ public void testCycles3() { DiGraph<String, String> g = LinkedDirectedGraph.create(); g.createDirectedGraphNode("a"); g.createDirectedGraphNode("b"); g.createDirectedGraphNode("c"); g.createDirectedGraphNode("d"); g.connect("a", "-", "b"); g.connect("b", "-", "c"); g.connect("c", "-", "b"); g.connect("b", "-", "d"); g.connect("c", "-", "d"); assertGood(createTest(g, "a", "d", Predicates.equalTo("a"), ALL_EDGE)); assertBad(createTest(g, "a", "d", Predicates.equalTo("z"), ALL_EDGE)); } /** * Much of the tests are done by testing all paths. We quickly verified * that some paths are indeed correct for the some path case. */ public void testSomePath1() { DiGraph<String, String> g = LinkedDirectedGraph.create(); g.createDirectedGraphNode("a"); g.createDirectedGraphNode("b"); g.createDirectedGraphNode("c"); g.createDirectedGraphNode("d"); g.connect("a", "-", "b"); g.connect("a", "-", "c"); g.connect("b", "-", "d"); g.connect("c", "-", "d"); assertTrue(createTest(g, "a", "d", Predicates.equalTo("b"), ALL_EDGE) .somePathsSatisfyPredicate()); assertTrue(createTest(g, "a", "d", Predicates.equalTo("c"), ALL_EDGE) .somePathsSatisfyPredicate()); assertTrue(createTest(g, "a", "d", Predicates.equalTo("a"), ALL_EDGE) .somePathsSatisfyPredicate()); assertTrue(createTest(g, "a", "d", Predicates.equalTo("d"), ALL_EDGE) .somePathsSatisfyPredicate()); assertFalse(createTest(g, "a", "d", Predicates.equalTo("NONE"), ALL_EDGE) .somePathsSatisfyPredicate()); } public void testSomePath2() { // No Paths between nodes, by definition, always false. DiGraph<String, String> g = LinkedDirectedGraph.create(); g.createDirectedGraphNode("a"); g.createDirectedGraphNode("b"); assertFalse(createTest(g, "a", "b", Predicates.equalTo("b"), ALL_EDGE) .somePathsSatisfyPredicate()); assertFalse(createTest(g, "a", "b", Predicates.equalTo("d"), ALL_EDGE) .somePathsSatisfyPredicate()); assertTrue(createTest(g, "a", "b", Predicates.equalTo("a"), ALL_EDGE) .somePathsSatisfyPredicate()); } public void testSomePathRevisiting() { DiGraph<String, String> g = LinkedDirectedGraph.create(); g.createDirectedGraphNode("1"); g.createDirectedGraphNode("2a"); g.createDirectedGraphNode("2b"); g.createDirectedGraphNode("3"); g.createDirectedGraphNode("4a"); g.createDirectedGraphNode("4b"); g.createDirectedGraphNode("5"); g.connect("1", "-", "2a"); g.connect("1", "-", "2b"); g.connect("2a", "-", "3"); g.connect("2b", "-", "3"); g.connect("3", "-", "4a"); g.connect("3", "-", "4b"); g.connect("4a", "-", "5"); g.connect("4b", "-", "5"); CountingPredicate<String> p = new CountingPredicate<String>(Predicates.equalTo("4a")); assertTrue(createTest(g, "1", "5", p, ALL_EDGE) .somePathsSatisfyPredicate()); // Make sure we are not doing more traversals than we have to. assertEquals(4, p.count); } public void testNonInclusive() { // No Paths between nodes, by definition, always false. DiGraph<String, String> g = LinkedDirectedGraph.create(); g.createDirectedGraphNode("a"); g.createDirectedGraphNode("b"); g.createDirectedGraphNode("c"); g.connect("a", "-", "b"); g.connect("b", "-", "c"); assertFalse(createNonInclusiveTest(g, "a", "b", Predicates.equalTo("a"), ALL_EDGE).somePathsSatisfyPredicate()); assertFalse(createNonInclusiveTest(g, "a", "b", Predicates.equalTo("b"), ALL_EDGE).somePathsSatisfyPredicate()); assertTrue(createNonInclusiveTest(g, "a", "c", Predicates.equalTo("b"), ALL_EDGE).somePathsSatisfyPredicate()); } private static <N, E> void assertGood(CheckPathsBetweenNodes<N, E> test) { assertTrue(test.allPathsSatisfyPredicate()); } private static <N, E> void assertBad(CheckPathsBetweenNodes<N, E> test) { assertFalse(test.allPathsSatisfyPredicate()); } private static CheckPathsBetweenNodes<String, String> createTest( DiGraph<String, String> graph, String entry, String exit, Predicate<String> nodePredicate, Predicate<DiGraphEdge<String, String>> edgePredicate) { return new CheckPathsBetweenNodes<String, String>(graph, graph.getDirectedGraphNode(entry), graph.getDirectedGraphNode(exit), nodePredicate, edgePredicate); } private static CheckPathsBetweenNodes<String, String> createNonInclusiveTest( DiGraph<String, String> graph, String entry, String exit, Predicate<String> nodePredicate, Predicate<DiGraphEdge<String, String>> edgePredicate) { return new CheckPathsBetweenNodes<String, String>(graph, graph.getDirectedGraphNode(entry), graph.getDirectedGraphNode(exit), nodePredicate, edgePredicate, false); } private static Predicate<DiGraphEdge<String, String>> edgeIs(final Object val) { return new Predicate<DiGraphEdge<String, String>>() { @Override public boolean apply(DiGraphEdge<String, String> input) { return input.getValue().equals(val); } }; } private static class CountingPredicate<T> implements Predicate<T> { private int count = 0; private final Predicate<T> delegate; private CountingPredicate(Predicate<T> delegate) { this.delegate = delegate; } @Override public boolean apply(T input) { count ++; return delegate.apply(input); } } }
[ { "be_test_class_file": "com/google/javascript/jscomp/CheckPathsBetweenNodes.java", "be_test_class_name": "com.google.javascript.jscomp.CheckPathsBetweenNodes", "be_test_function_name": "allPathsSatisfyPredicate", "be_test_function_signature": "()Z", "line_numbers": [ "111", "112", "113", "114" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/CheckPathsBetweenNodes.java", "be_test_class_name": "com.google.javascript.jscomp.CheckPathsBetweenNodes", "be_test_function_name": "checkAllPathsWithoutBackEdges", "be_test_function_signature": "(Lcom/google/javascript/jscomp/graph/DiGraph$DiGraphNode;Lcom/google/javascript/jscomp/graph/DiGraph$DiGraphNode;)Z", "line_numbers": [ "165", "167", "169", "170", "172", "175", "176", "178", "180", "181", "183", "184", "187", "188", "189", "191", "192" ], "method_line_rate": 0.7647058823529411 }, { "be_test_class_file": "com/google/javascript/jscomp/CheckPathsBetweenNodes.java", "be_test_class_name": "com.google.javascript.jscomp.CheckPathsBetweenNodes", "be_test_function_name": "discoverBackEdges", "be_test_function_signature": "(Lcom/google/javascript/jscomp/graph/DiGraph$DiGraphNode;)V", "line_numbers": [ "140", "141", "142", "143", "145", "146", "147", "148", "149", "151", "152", "153" ], "method_line_rate": 0.9166666666666666 }, { "be_test_class_file": "com/google/javascript/jscomp/CheckPathsBetweenNodes.java", "be_test_class_name": "com.google.javascript.jscomp.CheckPathsBetweenNodes", "be_test_function_name": "ignoreEdge", "be_test_function_signature": "(Lcom/google/javascript/jscomp/graph/DiGraph$DiGraphEdge;)Z", "line_numbers": [ "156" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/CheckPathsBetweenNodes.java", "be_test_class_name": "com.google.javascript.jscomp.CheckPathsBetweenNodes", "be_test_function_name": "setUp", "be_test_function_signature": "()V", "line_numbers": [ "129", "130", "131", "132" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/CheckPathsBetweenNodes.java", "be_test_class_name": "com.google.javascript.jscomp.CheckPathsBetweenNodes", "be_test_function_name": "tearDown", "be_test_function_signature": "()V", "line_numbers": [ "135", "136", "137" ], "method_line_rate": 1 } ]
public class Base64Test
@Test public void testRfc4648Section10Decode() { assertEquals("", StringUtils.newStringUsAscii(Base64.decodeBase64(""))); assertEquals("f", StringUtils.newStringUsAscii(Base64.decodeBase64("Zg=="))); assertEquals("fo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm8="))); assertEquals("foo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9v"))); assertEquals("foob", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYg=="))); assertEquals("fooba", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmE="))); assertEquals("foobar", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmFy"))); }
// public Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe); // public boolean isUrlSafe(); // @Override // void encode(final byte[] in, int inPos, final int inAvail, final Context context); // @Override // void decode(final byte[] in, int inPos, final int inAvail, final Context context); // @Deprecated // public static boolean isArrayByteBase64(final byte[] arrayOctet); // public static boolean isBase64(final byte octet); // public static boolean isBase64(final String base64); // public static boolean isBase64(final byte[] arrayOctet); // public static byte[] encodeBase64(final byte[] binaryData); // public static String encodeBase64String(final byte[] binaryData); // public static byte[] encodeBase64URLSafe(final byte[] binaryData); // public static String encodeBase64URLSafeString(final byte[] binaryData); // public static byte[] encodeBase64Chunked(final byte[] binaryData); // public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked); // public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe); // public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, // final boolean urlSafe, final int maxResultSize); // public static byte[] decodeBase64(final String base64String); // public static byte[] decodeBase64(final byte[] base64Data); // public static BigInteger decodeInteger(final byte[] pArray); // public static byte[] encodeInteger(final BigInteger bigInt); // static byte[] toIntegerBytes(final BigInteger bigInt); // @Override // protected boolean isInAlphabet(final byte octet); // } // // // Abstract Java Test Class // package org.apache.commons.codec.binary; // // 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.math.BigInteger; // import java.nio.charset.Charset; // import java.util.Arrays; // import java.util.Random; // import org.apache.commons.codec.Charsets; // import org.apache.commons.codec.DecoderException; // import org.apache.commons.codec.EncoderException; // import org.apache.commons.lang3.ArrayUtils; // import org.junit.Ignore; // import org.junit.Test; // // // // public class Base64Test { // private static final Charset CHARSET_UTF8 = Charsets.UTF_8; // private final Random random = new Random(); // // public Random getRandom(); // @Test // public void testIsStringBase64(); // @Test // public void testBase64(); // @Test // public void testBase64AtBufferStart(); // @Test // public void testBase64AtBufferEnd(); // @Test // public void testBase64AtBufferMiddle(); // private void testBase64InBuffer(int startPasSize, int endPadSize); // @Test // public void testDecodeWithInnerPad(); // @Test // public void testChunkedEncodeMultipleOf76(); // @Test // public void testCodec68(); // @Test // public void testCodeInteger1(); // @Test // public void testCodeInteger2(); // @Test // public void testCodeInteger3(); // @Test // public void testCodeInteger4(); // @Test // public void testCodeIntegerEdgeCases(); // @Test // public void testCodeIntegerNull(); // @Test // public void testConstructors(); // @Test // public void testConstructor_Int_ByteArray_Boolean(); // @Test // public void testConstructor_Int_ByteArray_Boolean_UrlSafe(); // @Test // public void testDecodePadMarkerIndex2(); // @Test // public void testDecodePadMarkerIndex3(); // @Test // public void testDecodePadOnly(); // @Test // public void testDecodePadOnlyChunked(); // @Test // public void testDecodeWithWhitespace() throws Exception; // @Test // public void testEmptyBase64(); // @Test // public void testEncodeDecodeRandom(); // @Test // public void testEncodeDecodeSmall(); // @Test // public void testEncodeOverMaxSize() throws Exception; // @Test // public void testCodec112(); // private void testEncodeOverMaxSize(final int maxSize) throws Exception; // @Test // public void testIgnoringNonBase64InDecode() throws Exception; // @Test // public void testIsArrayByteBase64(); // @Test // public void testIsUrlSafe(); // @Test // public void testKnownDecodings(); // @Test // public void testKnownEncodings(); // @Test // public void testNonBase64Test() throws Exception; // @Test // public void testObjectDecodeWithInvalidParameter() throws Exception; // @Test // public void testObjectDecodeWithValidParameter() throws Exception; // @Test // public void testObjectEncodeWithInvalidParameter() throws Exception; // @Test // public void testObjectEncodeWithValidParameter() throws Exception; // @Test // public void testObjectEncode() throws Exception; // @Test // public void testPairs(); // @Test // public void testRfc2045Section2Dot1CrLfDefinition(); // @Test // public void testRfc2045Section6Dot8ChunkSizeDefinition(); // @Test // public void testRfc1421Section6Dot8ChunkSizeDefinition(); // @Test // public void testRfc4648Section10Decode(); // @Test // public void testRfc4648Section10DecodeWithCrLf(); // @Test // public void testRfc4648Section10Encode(); // @Test // public void testRfc4648Section10DecodeEncode(); // private void testDecodeEncode(final String encodedText); // @Test // public void testRfc4648Section10EncodeDecode(); // private void testEncodeDecode(final String plainText); // @Test // public void testSingletons(); // @Test // public void testSingletonsChunked(); // @Test // public void testTriplets(); // @Test // public void testTripletsChunked(); // @Test // public void testUrlSafe(); // @Test // public void testUUID() throws DecoderException; // @Test // public void testByteToStringVariations() throws DecoderException; // @Test // public void testStringToByteVariations() throws DecoderException; // private String toString(final byte[] data); // @Test // @Ignore // public void testHugeLineSeparator(); // } // You are a professional Java test case writer, please create a test case named `testRfc4648Section10Decode` for the `Base64` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests RFC 4648 section 10 test vectors. * <ul> * <li>BASE64("") = ""</li> * <li>BASE64("f") = "Zg=="</li> * <li>BASE64("fo") = "Zm8="</li> * <li>BASE64("foo") = "Zm9v"</li> * <li>BASE64("foob") = "Zm9vYg=="</li> * <li>BASE64("fooba") = "Zm9vYmE="</li> * <li>BASE64("foobar") = "Zm9vYmFy"</li> * </ul> * * @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/ * html/rfc4648</a> */
src/test/java/org/apache/commons/codec/binary/Base64Test.java
package org.apache.commons.codec.binary; import java.math.BigInteger;
public Base64(); public Base64(final boolean urlSafe); public Base64(final int lineLength); public Base64(final int lineLength, final byte[] lineSeparator); public Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe); public boolean isUrlSafe(); @Override void encode(final byte[] in, int inPos, final int inAvail, final Context context); @Override void decode(final byte[] in, int inPos, final int inAvail, final Context context); @Deprecated public static boolean isArrayByteBase64(final byte[] arrayOctet); public static boolean isBase64(final byte octet); public static boolean isBase64(final String base64); public static boolean isBase64(final byte[] arrayOctet); public static byte[] encodeBase64(final byte[] binaryData); public static String encodeBase64String(final byte[] binaryData); public static byte[] encodeBase64URLSafe(final byte[] binaryData); public static String encodeBase64URLSafeString(final byte[] binaryData); public static byte[] encodeBase64Chunked(final byte[] binaryData); public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked); public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe); public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe, final int maxResultSize); public static byte[] decodeBase64(final String base64String); public static byte[] decodeBase64(final byte[] base64Data); public static BigInteger decodeInteger(final byte[] pArray); public static byte[] encodeInteger(final BigInteger bigInt); static byte[] toIntegerBytes(final BigInteger bigInt); @Override protected boolean isInAlphabet(final byte octet);
643
testRfc4648Section10Decode
```java public Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe); public boolean isUrlSafe(); @Override void encode(final byte[] in, int inPos, final int inAvail, final Context context); @Override void decode(final byte[] in, int inPos, final int inAvail, final Context context); @Deprecated public static boolean isArrayByteBase64(final byte[] arrayOctet); public static boolean isBase64(final byte octet); public static boolean isBase64(final String base64); public static boolean isBase64(final byte[] arrayOctet); public static byte[] encodeBase64(final byte[] binaryData); public static String encodeBase64String(final byte[] binaryData); public static byte[] encodeBase64URLSafe(final byte[] binaryData); public static String encodeBase64URLSafeString(final byte[] binaryData); public static byte[] encodeBase64Chunked(final byte[] binaryData); public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked); public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe); public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe, final int maxResultSize); public static byte[] decodeBase64(final String base64String); public static byte[] decodeBase64(final byte[] base64Data); public static BigInteger decodeInteger(final byte[] pArray); public static byte[] encodeInteger(final BigInteger bigInt); static byte[] toIntegerBytes(final BigInteger bigInt); @Override protected boolean isInAlphabet(final byte octet); } // Abstract Java Test Class package org.apache.commons.codec.binary; 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.math.BigInteger; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Random; import org.apache.commons.codec.Charsets; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.EncoderException; import org.apache.commons.lang3.ArrayUtils; import org.junit.Ignore; import org.junit.Test; public class Base64Test { private static final Charset CHARSET_UTF8 = Charsets.UTF_8; private final Random random = new Random(); public Random getRandom(); @Test public void testIsStringBase64(); @Test public void testBase64(); @Test public void testBase64AtBufferStart(); @Test public void testBase64AtBufferEnd(); @Test public void testBase64AtBufferMiddle(); private void testBase64InBuffer(int startPasSize, int endPadSize); @Test public void testDecodeWithInnerPad(); @Test public void testChunkedEncodeMultipleOf76(); @Test public void testCodec68(); @Test public void testCodeInteger1(); @Test public void testCodeInteger2(); @Test public void testCodeInteger3(); @Test public void testCodeInteger4(); @Test public void testCodeIntegerEdgeCases(); @Test public void testCodeIntegerNull(); @Test public void testConstructors(); @Test public void testConstructor_Int_ByteArray_Boolean(); @Test public void testConstructor_Int_ByteArray_Boolean_UrlSafe(); @Test public void testDecodePadMarkerIndex2(); @Test public void testDecodePadMarkerIndex3(); @Test public void testDecodePadOnly(); @Test public void testDecodePadOnlyChunked(); @Test public void testDecodeWithWhitespace() throws Exception; @Test public void testEmptyBase64(); @Test public void testEncodeDecodeRandom(); @Test public void testEncodeDecodeSmall(); @Test public void testEncodeOverMaxSize() throws Exception; @Test public void testCodec112(); private void testEncodeOverMaxSize(final int maxSize) throws Exception; @Test public void testIgnoringNonBase64InDecode() throws Exception; @Test public void testIsArrayByteBase64(); @Test public void testIsUrlSafe(); @Test public void testKnownDecodings(); @Test public void testKnownEncodings(); @Test public void testNonBase64Test() throws Exception; @Test public void testObjectDecodeWithInvalidParameter() throws Exception; @Test public void testObjectDecodeWithValidParameter() throws Exception; @Test public void testObjectEncodeWithInvalidParameter() throws Exception; @Test public void testObjectEncodeWithValidParameter() throws Exception; @Test public void testObjectEncode() throws Exception; @Test public void testPairs(); @Test public void testRfc2045Section2Dot1CrLfDefinition(); @Test public void testRfc2045Section6Dot8ChunkSizeDefinition(); @Test public void testRfc1421Section6Dot8ChunkSizeDefinition(); @Test public void testRfc4648Section10Decode(); @Test public void testRfc4648Section10DecodeWithCrLf(); @Test public void testRfc4648Section10Encode(); @Test public void testRfc4648Section10DecodeEncode(); private void testDecodeEncode(final String encodedText); @Test public void testRfc4648Section10EncodeDecode(); private void testEncodeDecode(final String plainText); @Test public void testSingletons(); @Test public void testSingletonsChunked(); @Test public void testTriplets(); @Test public void testTripletsChunked(); @Test public void testUrlSafe(); @Test public void testUUID() throws DecoderException; @Test public void testByteToStringVariations() throws DecoderException; @Test public void testStringToByteVariations() throws DecoderException; private String toString(final byte[] data); @Test @Ignore public void testHugeLineSeparator(); } ``` You are a professional Java test case writer, please create a test case named `testRfc4648Section10Decode` for the `Base64` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests RFC 4648 section 10 test vectors. * <ul> * <li>BASE64("") = ""</li> * <li>BASE64("f") = "Zg=="</li> * <li>BASE64("fo") = "Zm8="</li> * <li>BASE64("foo") = "Zm9v"</li> * <li>BASE64("foob") = "Zm9vYg=="</li> * <li>BASE64("fooba") = "Zm9vYmE="</li> * <li>BASE64("foobar") = "Zm9vYmFy"</li> * </ul> * * @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/ * html/rfc4648</a> */
634
// public Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe); // public boolean isUrlSafe(); // @Override // void encode(final byte[] in, int inPos, final int inAvail, final Context context); // @Override // void decode(final byte[] in, int inPos, final int inAvail, final Context context); // @Deprecated // public static boolean isArrayByteBase64(final byte[] arrayOctet); // public static boolean isBase64(final byte octet); // public static boolean isBase64(final String base64); // public static boolean isBase64(final byte[] arrayOctet); // public static byte[] encodeBase64(final byte[] binaryData); // public static String encodeBase64String(final byte[] binaryData); // public static byte[] encodeBase64URLSafe(final byte[] binaryData); // public static String encodeBase64URLSafeString(final byte[] binaryData); // public static byte[] encodeBase64Chunked(final byte[] binaryData); // public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked); // public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe); // public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, // final boolean urlSafe, final int maxResultSize); // public static byte[] decodeBase64(final String base64String); // public static byte[] decodeBase64(final byte[] base64Data); // public static BigInteger decodeInteger(final byte[] pArray); // public static byte[] encodeInteger(final BigInteger bigInt); // static byte[] toIntegerBytes(final BigInteger bigInt); // @Override // protected boolean isInAlphabet(final byte octet); // } // // // Abstract Java Test Class // package org.apache.commons.codec.binary; // // 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.math.BigInteger; // import java.nio.charset.Charset; // import java.util.Arrays; // import java.util.Random; // import org.apache.commons.codec.Charsets; // import org.apache.commons.codec.DecoderException; // import org.apache.commons.codec.EncoderException; // import org.apache.commons.lang3.ArrayUtils; // import org.junit.Ignore; // import org.junit.Test; // // // // public class Base64Test { // private static final Charset CHARSET_UTF8 = Charsets.UTF_8; // private final Random random = new Random(); // // public Random getRandom(); // @Test // public void testIsStringBase64(); // @Test // public void testBase64(); // @Test // public void testBase64AtBufferStart(); // @Test // public void testBase64AtBufferEnd(); // @Test // public void testBase64AtBufferMiddle(); // private void testBase64InBuffer(int startPasSize, int endPadSize); // @Test // public void testDecodeWithInnerPad(); // @Test // public void testChunkedEncodeMultipleOf76(); // @Test // public void testCodec68(); // @Test // public void testCodeInteger1(); // @Test // public void testCodeInteger2(); // @Test // public void testCodeInteger3(); // @Test // public void testCodeInteger4(); // @Test // public void testCodeIntegerEdgeCases(); // @Test // public void testCodeIntegerNull(); // @Test // public void testConstructors(); // @Test // public void testConstructor_Int_ByteArray_Boolean(); // @Test // public void testConstructor_Int_ByteArray_Boolean_UrlSafe(); // @Test // public void testDecodePadMarkerIndex2(); // @Test // public void testDecodePadMarkerIndex3(); // @Test // public void testDecodePadOnly(); // @Test // public void testDecodePadOnlyChunked(); // @Test // public void testDecodeWithWhitespace() throws Exception; // @Test // public void testEmptyBase64(); // @Test // public void testEncodeDecodeRandom(); // @Test // public void testEncodeDecodeSmall(); // @Test // public void testEncodeOverMaxSize() throws Exception; // @Test // public void testCodec112(); // private void testEncodeOverMaxSize(final int maxSize) throws Exception; // @Test // public void testIgnoringNonBase64InDecode() throws Exception; // @Test // public void testIsArrayByteBase64(); // @Test // public void testIsUrlSafe(); // @Test // public void testKnownDecodings(); // @Test // public void testKnownEncodings(); // @Test // public void testNonBase64Test() throws Exception; // @Test // public void testObjectDecodeWithInvalidParameter() throws Exception; // @Test // public void testObjectDecodeWithValidParameter() throws Exception; // @Test // public void testObjectEncodeWithInvalidParameter() throws Exception; // @Test // public void testObjectEncodeWithValidParameter() throws Exception; // @Test // public void testObjectEncode() throws Exception; // @Test // public void testPairs(); // @Test // public void testRfc2045Section2Dot1CrLfDefinition(); // @Test // public void testRfc2045Section6Dot8ChunkSizeDefinition(); // @Test // public void testRfc1421Section6Dot8ChunkSizeDefinition(); // @Test // public void testRfc4648Section10Decode(); // @Test // public void testRfc4648Section10DecodeWithCrLf(); // @Test // public void testRfc4648Section10Encode(); // @Test // public void testRfc4648Section10DecodeEncode(); // private void testDecodeEncode(final String encodedText); // @Test // public void testRfc4648Section10EncodeDecode(); // private void testEncodeDecode(final String plainText); // @Test // public void testSingletons(); // @Test // public void testSingletonsChunked(); // @Test // public void testTriplets(); // @Test // public void testTripletsChunked(); // @Test // public void testUrlSafe(); // @Test // public void testUUID() throws DecoderException; // @Test // public void testByteToStringVariations() throws DecoderException; // @Test // public void testStringToByteVariations() throws DecoderException; // private String toString(final byte[] data); // @Test // @Ignore // public void testHugeLineSeparator(); // } // You are a professional Java test case writer, please create a test case named `testRfc4648Section10Decode` for the `Base64` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests RFC 4648 section 10 test vectors. * <ul> * <li>BASE64("") = ""</li> * <li>BASE64("f") = "Zg=="</li> * <li>BASE64("fo") = "Zm8="</li> * <li>BASE64("foo") = "Zm9v"</li> * <li>BASE64("foob") = "Zm9vYg=="</li> * <li>BASE64("fooba") = "Zm9vYmE="</li> * <li>BASE64("foobar") = "Zm9vYmFy"</li> * </ul> * * @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/ * html/rfc4648</a> */ @Test public void testRfc4648Section10Decode() {
/** * Tests RFC 4648 section 10 test vectors. * <ul> * <li>BASE64("") = ""</li> * <li>BASE64("f") = "Zg=="</li> * <li>BASE64("fo") = "Zm8="</li> * <li>BASE64("foo") = "Zm9v"</li> * <li>BASE64("foob") = "Zm9vYg=="</li> * <li>BASE64("fooba") = "Zm9vYmE="</li> * <li>BASE64("foobar") = "Zm9vYmFy"</li> * </ul> * * @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/ * html/rfc4648</a> */
18
org.apache.commons.codec.binary.Base64
src/test/java
```java public Base64(final int lineLength, final byte[] lineSeparator, final boolean urlSafe); public boolean isUrlSafe(); @Override void encode(final byte[] in, int inPos, final int inAvail, final Context context); @Override void decode(final byte[] in, int inPos, final int inAvail, final Context context); @Deprecated public static boolean isArrayByteBase64(final byte[] arrayOctet); public static boolean isBase64(final byte octet); public static boolean isBase64(final String base64); public static boolean isBase64(final byte[] arrayOctet); public static byte[] encodeBase64(final byte[] binaryData); public static String encodeBase64String(final byte[] binaryData); public static byte[] encodeBase64URLSafe(final byte[] binaryData); public static String encodeBase64URLSafeString(final byte[] binaryData); public static byte[] encodeBase64Chunked(final byte[] binaryData); public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked); public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe); public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe, final int maxResultSize); public static byte[] decodeBase64(final String base64String); public static byte[] decodeBase64(final byte[] base64Data); public static BigInteger decodeInteger(final byte[] pArray); public static byte[] encodeInteger(final BigInteger bigInt); static byte[] toIntegerBytes(final BigInteger bigInt); @Override protected boolean isInAlphabet(final byte octet); } // Abstract Java Test Class package org.apache.commons.codec.binary; 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.math.BigInteger; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Random; import org.apache.commons.codec.Charsets; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.EncoderException; import org.apache.commons.lang3.ArrayUtils; import org.junit.Ignore; import org.junit.Test; public class Base64Test { private static final Charset CHARSET_UTF8 = Charsets.UTF_8; private final Random random = new Random(); public Random getRandom(); @Test public void testIsStringBase64(); @Test public void testBase64(); @Test public void testBase64AtBufferStart(); @Test public void testBase64AtBufferEnd(); @Test public void testBase64AtBufferMiddle(); private void testBase64InBuffer(int startPasSize, int endPadSize); @Test public void testDecodeWithInnerPad(); @Test public void testChunkedEncodeMultipleOf76(); @Test public void testCodec68(); @Test public void testCodeInteger1(); @Test public void testCodeInteger2(); @Test public void testCodeInteger3(); @Test public void testCodeInteger4(); @Test public void testCodeIntegerEdgeCases(); @Test public void testCodeIntegerNull(); @Test public void testConstructors(); @Test public void testConstructor_Int_ByteArray_Boolean(); @Test public void testConstructor_Int_ByteArray_Boolean_UrlSafe(); @Test public void testDecodePadMarkerIndex2(); @Test public void testDecodePadMarkerIndex3(); @Test public void testDecodePadOnly(); @Test public void testDecodePadOnlyChunked(); @Test public void testDecodeWithWhitespace() throws Exception; @Test public void testEmptyBase64(); @Test public void testEncodeDecodeRandom(); @Test public void testEncodeDecodeSmall(); @Test public void testEncodeOverMaxSize() throws Exception; @Test public void testCodec112(); private void testEncodeOverMaxSize(final int maxSize) throws Exception; @Test public void testIgnoringNonBase64InDecode() throws Exception; @Test public void testIsArrayByteBase64(); @Test public void testIsUrlSafe(); @Test public void testKnownDecodings(); @Test public void testKnownEncodings(); @Test public void testNonBase64Test() throws Exception; @Test public void testObjectDecodeWithInvalidParameter() throws Exception; @Test public void testObjectDecodeWithValidParameter() throws Exception; @Test public void testObjectEncodeWithInvalidParameter() throws Exception; @Test public void testObjectEncodeWithValidParameter() throws Exception; @Test public void testObjectEncode() throws Exception; @Test public void testPairs(); @Test public void testRfc2045Section2Dot1CrLfDefinition(); @Test public void testRfc2045Section6Dot8ChunkSizeDefinition(); @Test public void testRfc1421Section6Dot8ChunkSizeDefinition(); @Test public void testRfc4648Section10Decode(); @Test public void testRfc4648Section10DecodeWithCrLf(); @Test public void testRfc4648Section10Encode(); @Test public void testRfc4648Section10DecodeEncode(); private void testDecodeEncode(final String encodedText); @Test public void testRfc4648Section10EncodeDecode(); private void testEncodeDecode(final String plainText); @Test public void testSingletons(); @Test public void testSingletonsChunked(); @Test public void testTriplets(); @Test public void testTripletsChunked(); @Test public void testUrlSafe(); @Test public void testUUID() throws DecoderException; @Test public void testByteToStringVariations() throws DecoderException; @Test public void testStringToByteVariations() throws DecoderException; private String toString(final byte[] data); @Test @Ignore public void testHugeLineSeparator(); } ``` You are a professional Java test case writer, please create a test case named `testRfc4648Section10Decode` for the `Base64` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests RFC 4648 section 10 test vectors. * <ul> * <li>BASE64("") = ""</li> * <li>BASE64("f") = "Zg=="</li> * <li>BASE64("fo") = "Zm8="</li> * <li>BASE64("foo") = "Zm9v"</li> * <li>BASE64("foob") = "Zm9vYg=="</li> * <li>BASE64("fooba") = "Zm9vYmE="</li> * <li>BASE64("foobar") = "Zm9vYmFy"</li> * </ul> * * @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/ * html/rfc4648</a> */ @Test public void testRfc4648Section10Decode() { ```
public class Base64 extends BaseNCodec
package org.apache.commons.codec.binary; 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.math.BigInteger; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Random; import org.apache.commons.codec.Charsets; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.EncoderException; import org.apache.commons.lang3.ArrayUtils; import org.junit.Ignore; import org.junit.Test;
public Random getRandom(); @Test public void testIsStringBase64(); @Test public void testBase64(); @Test public void testBase64AtBufferStart(); @Test public void testBase64AtBufferEnd(); @Test public void testBase64AtBufferMiddle(); private void testBase64InBuffer(int startPasSize, int endPadSize); @Test public void testDecodeWithInnerPad(); @Test public void testChunkedEncodeMultipleOf76(); @Test public void testCodec68(); @Test public void testCodeInteger1(); @Test public void testCodeInteger2(); @Test public void testCodeInteger3(); @Test public void testCodeInteger4(); @Test public void testCodeIntegerEdgeCases(); @Test public void testCodeIntegerNull(); @Test public void testConstructors(); @Test public void testConstructor_Int_ByteArray_Boolean(); @Test public void testConstructor_Int_ByteArray_Boolean_UrlSafe(); @Test public void testDecodePadMarkerIndex2(); @Test public void testDecodePadMarkerIndex3(); @Test public void testDecodePadOnly(); @Test public void testDecodePadOnlyChunked(); @Test public void testDecodeWithWhitespace() throws Exception; @Test public void testEmptyBase64(); @Test public void testEncodeDecodeRandom(); @Test public void testEncodeDecodeSmall(); @Test public void testEncodeOverMaxSize() throws Exception; @Test public void testCodec112(); private void testEncodeOverMaxSize(final int maxSize) throws Exception; @Test public void testIgnoringNonBase64InDecode() throws Exception; @Test public void testIsArrayByteBase64(); @Test public void testIsUrlSafe(); @Test public void testKnownDecodings(); @Test public void testKnownEncodings(); @Test public void testNonBase64Test() throws Exception; @Test public void testObjectDecodeWithInvalidParameter() throws Exception; @Test public void testObjectDecodeWithValidParameter() throws Exception; @Test public void testObjectEncodeWithInvalidParameter() throws Exception; @Test public void testObjectEncodeWithValidParameter() throws Exception; @Test public void testObjectEncode() throws Exception; @Test public void testPairs(); @Test public void testRfc2045Section2Dot1CrLfDefinition(); @Test public void testRfc2045Section6Dot8ChunkSizeDefinition(); @Test public void testRfc1421Section6Dot8ChunkSizeDefinition(); @Test public void testRfc4648Section10Decode(); @Test public void testRfc4648Section10DecodeWithCrLf(); @Test public void testRfc4648Section10Encode(); @Test public void testRfc4648Section10DecodeEncode(); private void testDecodeEncode(final String encodedText); @Test public void testRfc4648Section10EncodeDecode(); private void testEncodeDecode(final String plainText); @Test public void testSingletons(); @Test public void testSingletonsChunked(); @Test public void testTriplets(); @Test public void testTripletsChunked(); @Test public void testUrlSafe(); @Test public void testUUID() throws DecoderException; @Test public void testByteToStringVariations() throws DecoderException; @Test public void testStringToByteVariations() throws DecoderException; private String toString(final byte[] data); @Test @Ignore public void testHugeLineSeparator();
22e3f50d98d5262c58fa65b13854885b1974ed7a1133aa37e94d225fc5b905ae
[ "org.apache.commons.codec.binary.Base64Test::testRfc4648Section10Decode" ]
private static final int BITS_PER_ENCODED_BYTE = 6; private static final int BYTES_PER_UNENCODED_BLOCK = 3; private static final int BYTES_PER_ENCODED_BLOCK = 4; static final byte[] CHUNK_SEPARATOR = {'\r', '\n'}; private static final byte[] STANDARD_ENCODE_TABLE = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; private static final byte[] URL_SAFE_ENCODE_TABLE = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_' }; private static final byte[] DECODE_TABLE = { // 0 1 2 3 4 5 6 7 8 9 A B C D E F -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 00-0f -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10-1f -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63, // 20-2f + - / 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, // 30-3f 0-9 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 40-4f A-O 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63, // 50-5f P-Z _ -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // 60-6f a-o 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 // 70-7a p-z }; private static final int MASK_6BITS = 0x3f; private final byte[] encodeTable; private final byte[] decodeTable = DECODE_TABLE; private final byte[] lineSeparator; private final int decodeSize; private final int encodeSize;
@Test public void testRfc4648Section10Decode()
private static final Charset CHARSET_UTF8 = Charsets.UTF_8; private final Random random = new Random();
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.binary; 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.math.BigInteger; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Random; import org.apache.commons.codec.Charsets; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.EncoderException; import org.apache.commons.lang3.ArrayUtils; import org.junit.Ignore; import org.junit.Test; /** * Test cases for Base64 class. * * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a> * @version $Id$ */ public class Base64Test { private static final Charset CHARSET_UTF8 = Charsets.UTF_8; private final Random random = new Random(); /** * @return Returns the random. */ public Random getRandom() { return this.random; } /** * Test the isStringBase64 method. */ @Test public void testIsStringBase64() { final String nullString = null; final String emptyString = ""; final String validString = "abc===defg\n\r123456\r789\r\rABC\n\nDEF==GHI\r\nJKL=============="; final String invalidString = validString + (char) 0; // append null // character try { Base64.isBase64(nullString); fail("Base64.isStringBase64() should not be null-safe."); } catch (final NullPointerException npe) { assertNotNull("Base64.isStringBase64() should not be null-safe.", npe); } assertTrue("Base64.isStringBase64(empty-string) is true", Base64.isBase64(emptyString)); assertTrue("Base64.isStringBase64(valid-string) is true", Base64.isBase64(validString)); assertFalse("Base64.isStringBase64(invalid-string) is false", Base64.isBase64(invalidString)); } /** * Test the Base64 implementation */ @Test public void testBase64() { final String content = "Hello World"; String encodedContent; byte[] encodedBytes = Base64.encodeBase64(StringUtils.getBytesUtf8(content)); encodedContent = StringUtils.newStringUtf8(encodedBytes); assertEquals("encoding hello world", "SGVsbG8gV29ybGQ=", encodedContent); Base64 b64 = new Base64(BaseNCodec.MIME_CHUNK_SIZE, null); // null // lineSeparator // same as // saying // no-chunking encodedBytes = b64.encode(StringUtils.getBytesUtf8(content)); encodedContent = StringUtils.newStringUtf8(encodedBytes); assertEquals("encoding hello world", "SGVsbG8gV29ybGQ=", encodedContent); b64 = new Base64(0, null); // null lineSeparator same as saying // no-chunking encodedBytes = b64.encode(StringUtils.getBytesUtf8(content)); encodedContent = StringUtils.newStringUtf8(encodedBytes); assertEquals("encoding hello world", "SGVsbG8gV29ybGQ=", encodedContent); // bogus characters to decode (to skip actually) {e-acute*6} final byte[] decode = b64.decode("SGVsbG{\u00e9\u00e9\u00e9\u00e9\u00e9\u00e9}8gV29ybGQ="); final String decodeString = StringUtils.newStringUtf8(decode); assertEquals("decode hello world", "Hello World", decodeString); } @Test public void testBase64AtBufferStart() { testBase64InBuffer(0, 100); } @Test public void testBase64AtBufferEnd() { testBase64InBuffer(100, 0); } @Test public void testBase64AtBufferMiddle() { testBase64InBuffer(100, 100); } private void testBase64InBuffer(int startPasSize, int endPadSize) { final String content = "Hello World"; String encodedContent; final byte[] bytesUtf8 = StringUtils.getBytesUtf8(content); byte[] buffer = ArrayUtils.addAll(bytesUtf8, new byte[endPadSize]); buffer = ArrayUtils.addAll(new byte[startPasSize], buffer); byte[] encodedBytes = new Base64().encode(buffer, startPasSize, bytesUtf8.length); encodedContent = StringUtils.newStringUtf8(encodedBytes); assertEquals("encoding hello world", "SGVsbG8gV29ybGQ=", encodedContent); } /** * Test our decode with pad character in the middle. (Our current * implementation: halt decode and return what we've got so far). * * The point of this test is not to say * "this is the correct way to decode base64." The point is simply to keep * us aware of the current logic since 1.4 so we don't accidentally break it * without realizing. * * Note for historians. The 1.3 logic would decode to: * "Hello World\u0000Hello World" -- null in the middle --- and 1.4 * unwittingly changed it to current logic. */ @Test public void testDecodeWithInnerPad() { final String content = "SGVsbG8gV29ybGQ=SGVsbG8gV29ybGQ="; final byte[] result = Base64.decodeBase64(content); final byte[] shouldBe = StringUtils.getBytesUtf8("Hello World"); assertTrue("decode should halt at pad (=)", Arrays.equals(result, shouldBe)); } /** * Tests Base64.encodeBase64(). */ @Test public void testChunkedEncodeMultipleOf76() { final byte[] expectedEncode = Base64.encodeBase64(Base64TestData.DECODED, true); // convert to "\r\n" so we're equal to the old openssl encoding test // stored // in Base64TestData.ENCODED_76_CHARS_PER_LINE: final String actualResult = Base64TestData.ENCODED_76_CHARS_PER_LINE.replaceAll("\n", "\r\n"); final byte[] actualEncode = StringUtils.getBytesUtf8(actualResult); assertTrue("chunkedEncodeMultipleOf76", Arrays.equals(expectedEncode, actualEncode)); } /** * CODEC-68: isBase64 throws ArrayIndexOutOfBoundsException on some * non-BASE64 bytes */ @Test public void testCodec68() { final byte[] x = new byte[] { 'n', 'A', '=', '=', (byte) 0x9c }; Base64.decodeBase64(x); } @Test public void testCodeInteger1() { final String encodedInt1 = "li7dzDacuo67Jg7mtqEm2TRuOMU="; final BigInteger bigInt1 = new BigInteger("85739377120809420210425962799" + "0318636601332086981"); assertEquals(encodedInt1, new String(Base64.encodeInteger(bigInt1))); assertEquals(bigInt1, Base64.decodeInteger(encodedInt1.getBytes(CHARSET_UTF8))); } @Test public void testCodeInteger2() { final String encodedInt2 = "9B5ypLY9pMOmtxCeTDHgwdNFeGs="; final BigInteger bigInt2 = new BigInteger("13936727572861167254666467268" + "91466679477132949611"); assertEquals(encodedInt2, new String(Base64.encodeInteger(bigInt2))); assertEquals(bigInt2, Base64.decodeInteger(encodedInt2.getBytes(CHARSET_UTF8))); } @Test public void testCodeInteger3() { final String encodedInt3 = "FKIhdgaG5LGKiEtF1vHy4f3y700zaD6QwDS3IrNVGzNp2" + "rY+1LFWTK6D44AyiC1n8uWz1itkYMZF0/aKDK0Yjg=="; final BigInteger bigInt3 = new BigInteger( "10806548154093873461951748545" + "1196989136416448805819079363524309897749044958112417136240557" + "4495062430572478766856090958495998158114332651671116876320938126"); assertEquals(encodedInt3, new String(Base64.encodeInteger(bigInt3))); assertEquals(bigInt3, Base64.decodeInteger(encodedInt3.getBytes(CHARSET_UTF8))); } @Test public void testCodeInteger4() { final String encodedInt4 = "ctA8YGxrtngg/zKVvqEOefnwmViFztcnPBYPlJsvh6yKI" + "4iDm68fnp4Mi3RrJ6bZAygFrUIQLxLjV+OJtgJAEto0xAs+Mehuq1DkSFEpP3o" + "DzCTOsrOiS1DwQe4oIb7zVk/9l7aPtJMHW0LVlMdwZNFNNJoqMcT2ZfCPrfvYv" + "Q0="; final BigInteger bigInt4 = new BigInteger( "80624726256040348115552042320" + "6968135001872753709424419772586693950232350200555646471175944" + "519297087885987040810778908507262272892702303774422853675597" + "748008534040890923814202286633163248086055216976551456088015" + "338880713818192088877057717530169381044092839402438015097654" + "53542091716518238707344493641683483917"); assertEquals(encodedInt4, new String(Base64.encodeInteger(bigInt4))); assertEquals(bigInt4, Base64.decodeInteger(encodedInt4.getBytes(CHARSET_UTF8))); } @Test public void testCodeIntegerEdgeCases() { // TODO } @Test public void testCodeIntegerNull() { try { Base64.encodeInteger(null); fail("Exception not thrown when passing in null to encodeInteger(BigInteger)"); } catch (final NullPointerException npe) { // expected } catch (final Exception e) { fail("Incorrect Exception caught when passing in null to encodeInteger(BigInteger)"); } } @Test public void testConstructors() { Base64 base64; base64 = new Base64(); base64 = new Base64(-1); base64 = new Base64(-1, new byte[] {}); base64 = new Base64(64, new byte[] {}); try { base64 = new Base64(-1, new byte[] { 'A' }); // TODO do we need to // check sep if len // = -1? fail("Should have rejected attempt to use 'A' as a line separator"); } catch (final IllegalArgumentException ignored) { // Expected } try { base64 = new Base64(64, new byte[] { 'A' }); fail("Should have rejected attempt to use 'A' as a line separator"); } catch (final IllegalArgumentException ignored) { // Expected } try { base64 = new Base64(64, new byte[] { '=' }); fail("Should have rejected attempt to use '=' as a line separator"); } catch (final IllegalArgumentException ignored) { // Expected } base64 = new Base64(64, new byte[] { '$' }); // OK try { base64 = new Base64(64, new byte[] { 'A', '$' }); fail("Should have rejected attempt to use 'A$' as a line separator"); } catch (final IllegalArgumentException ignored) { // Expected } base64 = new Base64(64, new byte[] { ' ', '$', '\n', '\r', '\t' }); // OK assertNotNull(base64); } @Test public void testConstructor_Int_ByteArray_Boolean() { final Base64 base64 = new Base64(65, new byte[] { '\t' }, false); final byte[] encoded = base64.encode(Base64TestData.DECODED); String expectedResult = Base64TestData.ENCODED_64_CHARS_PER_LINE; expectedResult = expectedResult.replace('\n', '\t'); final String result = StringUtils.newStringUtf8(encoded); assertEquals("new Base64(65, \\t, false)", expectedResult, result); } @Test public void testConstructor_Int_ByteArray_Boolean_UrlSafe() { // url-safe variation final Base64 base64 = new Base64(64, new byte[] { '\t' }, true); final byte[] encoded = base64.encode(Base64TestData.DECODED); String expectedResult = Base64TestData.ENCODED_64_CHARS_PER_LINE; expectedResult = expectedResult.replaceAll("=", ""); // url-safe has no // == padding. expectedResult = expectedResult.replace('\n', '\t'); expectedResult = expectedResult.replace('+', '-'); expectedResult = expectedResult.replace('/', '_'); final String result = StringUtils.newStringUtf8(encoded); assertEquals("new Base64(64, \\t, true)", result, expectedResult); } /** * Tests conditional true branch for "marker0" test. */ @Test public void testDecodePadMarkerIndex2() { assertEquals("A", new String(Base64.decodeBase64("QQ==".getBytes(CHARSET_UTF8)))); } /** * Tests conditional branches for "marker1" test. */ @Test public void testDecodePadMarkerIndex3() { assertEquals("AA", new String(Base64.decodeBase64("QUE=".getBytes(CHARSET_UTF8)))); assertEquals("AAA", new String(Base64.decodeBase64("QUFB".getBytes(CHARSET_UTF8)))); } @Test public void testDecodePadOnly() { assertEquals(0, Base64.decodeBase64("====".getBytes(CHARSET_UTF8)).length); assertEquals("", new String(Base64.decodeBase64("====".getBytes(CHARSET_UTF8)))); // Test truncated padding assertEquals(0, Base64.decodeBase64("===".getBytes(CHARSET_UTF8)).length); assertEquals(0, Base64.decodeBase64("==".getBytes(CHARSET_UTF8)).length); assertEquals(0, Base64.decodeBase64("=".getBytes(CHARSET_UTF8)).length); assertEquals(0, Base64.decodeBase64("".getBytes(CHARSET_UTF8)).length); } @Test public void testDecodePadOnlyChunked() { assertEquals(0, Base64.decodeBase64("====\n".getBytes(CHARSET_UTF8)).length); assertEquals("", new String(Base64.decodeBase64("====\n".getBytes(CHARSET_UTF8)))); // Test truncated padding assertEquals(0, Base64.decodeBase64("===\n".getBytes(CHARSET_UTF8)).length); assertEquals(0, Base64.decodeBase64("==\n".getBytes(CHARSET_UTF8)).length); assertEquals(0, Base64.decodeBase64("=\n".getBytes(CHARSET_UTF8)).length); assertEquals(0, Base64.decodeBase64("\n".getBytes(CHARSET_UTF8)).length); } @Test public void testDecodeWithWhitespace() throws Exception { final String orig = "I am a late night coder."; final byte[] encodedArray = Base64.encodeBase64(orig.getBytes(CHARSET_UTF8)); final StringBuilder intermediate = new StringBuilder(new String(encodedArray)); intermediate.insert(2, ' '); intermediate.insert(5, '\t'); intermediate.insert(10, '\r'); intermediate.insert(15, '\n'); final byte[] encodedWithWS = intermediate.toString().getBytes(CHARSET_UTF8); final byte[] decodedWithWS = Base64.decodeBase64(encodedWithWS); final String dest = new String(decodedWithWS); assertEquals("Dest string doesn't equal the original", orig, dest); } /** * Test encode and decode of empty byte array. */ @Test public void testEmptyBase64() { byte[] empty = new byte[0]; byte[] result = Base64.encodeBase64(empty); assertEquals("empty base64 encode", 0, result.length); assertEquals("empty base64 encode", null, Base64.encodeBase64(null)); empty = new byte[0]; result = Base64.decodeBase64(empty); assertEquals("empty base64 decode", 0, result.length); assertEquals("empty base64 encode", null, Base64.decodeBase64((byte[]) null)); } // encode/decode a large random array @Test public void testEncodeDecodeRandom() { for (int i = 1; i < 5; i++) { final byte[] data = new byte[this.getRandom().nextInt(10000) + 1]; this.getRandom().nextBytes(data); final byte[] enc = Base64.encodeBase64(data); assertTrue(Base64.isBase64(enc)); final byte[] data2 = Base64.decodeBase64(enc); assertTrue(Arrays.equals(data, data2)); } } // encode/decode random arrays from size 0 to size 11 @Test public void testEncodeDecodeSmall() { for (int i = 0; i < 12; i++) { final byte[] data = new byte[i]; this.getRandom().nextBytes(data); final byte[] enc = Base64.encodeBase64(data); assertTrue("\"" + new String(enc) + "\" is Base64 data.", Base64.isBase64(enc)); final byte[] data2 = Base64.decodeBase64(enc); assertTrue(toString(data) + " equals " + toString(data2), Arrays.equals(data, data2)); } } @Test public void testEncodeOverMaxSize() throws Exception { testEncodeOverMaxSize(-1); testEncodeOverMaxSize(0); testEncodeOverMaxSize(1); testEncodeOverMaxSize(2); } @Test public void testCodec112() { // size calculation assumes always chunked final byte[] in = new byte[] { 0 }; final byte[] out = Base64.encodeBase64(in); Base64.encodeBase64(in, false, false, out.length); } private void testEncodeOverMaxSize(final int maxSize) throws Exception { try { Base64.encodeBase64(Base64TestData.DECODED, true, false, maxSize); fail("Expected " + IllegalArgumentException.class.getName()); } catch (final IllegalArgumentException e) { // Expected } } @Test public void testIgnoringNonBase64InDecode() throws Exception { assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64.decodeBase64( "VGhlIH@$#$@%F1aWN@#@#@@rIGJyb3duIGZve\n\r\t%#%#%#%CBqd##$#$W1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==" .getBytes(CHARSET_UTF8)))); } @Test public void testIsArrayByteBase64() { assertFalse(Base64.isBase64(new byte[] { Byte.MIN_VALUE })); assertFalse(Base64.isBase64(new byte[] { -125 })); assertFalse(Base64.isBase64(new byte[] { -10 })); assertFalse(Base64.isBase64(new byte[] { 0 })); assertFalse(Base64.isBase64(new byte[] { 64, Byte.MAX_VALUE })); assertFalse(Base64.isBase64(new byte[] { Byte.MAX_VALUE })); assertTrue(Base64.isBase64(new byte[] { 'A' })); assertFalse(Base64.isBase64(new byte[] { 'A', Byte.MIN_VALUE })); assertTrue(Base64.isBase64(new byte[] { 'A', 'Z', 'a' })); assertTrue(Base64.isBase64(new byte[] { '/', '=', '+' })); assertFalse(Base64.isBase64(new byte[] { '$' })); } /** * Tests isUrlSafe. */ @Test public void testIsUrlSafe() { final Base64 base64Standard = new Base64(false); final Base64 base64URLSafe = new Base64(true); assertFalse("Base64.isUrlSafe=false", base64Standard.isUrlSafe()); assertTrue("Base64.isUrlSafe=true", base64URLSafe.isUrlSafe()); final byte[] whiteSpace = { ' ', '\n', '\r', '\t' }; assertTrue("Base64.isBase64(whiteSpace)=true", Base64.isBase64(whiteSpace)); } @Test public void testKnownDecodings() { assertEquals("The quick brown fox jumped over the lazy dogs.", new String(Base64.decodeBase64( "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==".getBytes(CHARSET_UTF8)))); assertEquals("It was the best of times, it was the worst of times.", new String(Base64.decodeBase64( "SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==".getBytes(CHARSET_UTF8)))); assertEquals("http://jakarta.apache.org/commmons", new String( Base64.decodeBase64("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==".getBytes(CHARSET_UTF8)))); assertEquals("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz", new String(Base64.decodeBase64( "QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==".getBytes(CHARSET_UTF8)))); assertEquals("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", new String(Base64.decodeBase64("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=".getBytes(CHARSET_UTF8)))); assertEquals("xyzzy!", new String(Base64.decodeBase64("eHl6enkh".getBytes(CHARSET_UTF8)))); } @Test public void testKnownEncodings() { assertEquals("VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2dzLg==", new String( Base64.encodeBase64("The quick brown fox jumped over the lazy dogs.".getBytes(CHARSET_UTF8)))); assertEquals( "YmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJs\r\nYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFo\r\nIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBibGFoIGJsYWggYmxhaCBi\r\nbGFoIGJsYWg=\r\n", new String(Base64.encodeBase64Chunked( "blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah" .getBytes(CHARSET_UTF8)))); assertEquals("SXQgd2FzIHRoZSBiZXN0IG9mIHRpbWVzLCBpdCB3YXMgdGhlIHdvcnN0IG9mIHRpbWVzLg==", new String( Base64.encodeBase64("It was the best of times, it was the worst of times.".getBytes(CHARSET_UTF8)))); assertEquals("aHR0cDovL2pha2FydGEuYXBhY2hlLm9yZy9jb21tbW9ucw==", new String(Base64.encodeBase64("http://jakarta.apache.org/commmons".getBytes(CHARSET_UTF8)))); assertEquals("QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==", new String( Base64.encodeBase64("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz".getBytes(CHARSET_UTF8)))); assertEquals("eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=", new String(Base64.encodeBase64("{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }".getBytes(CHARSET_UTF8)))); assertEquals("eHl6enkh", new String(Base64.encodeBase64("xyzzy!".getBytes(CHARSET_UTF8)))); } @Test public void testNonBase64Test() throws Exception { final byte[] bArray = { '%' }; assertFalse("Invalid Base64 array was incorrectly validated as " + "an array of Base64 encoded data", Base64.isBase64(bArray)); try { final Base64 b64 = new Base64(); final byte[] result = b64.decode(bArray); assertEquals("The result should be empty as the test encoded content did " + "not contain any valid base 64 characters", 0, result.length); } catch (final Exception e) { fail("Exception was thrown when trying to decode " + "invalid base64 encoded data - RFC 2045 requires that all " + "non base64 character be discarded, an exception should not" + " have been thrown"); } } @Test public void testObjectDecodeWithInvalidParameter() throws Exception { final Base64 b64 = new Base64(); try { b64.decode(Integer.valueOf(5)); fail("decode(Object) didn't throw an exception when passed an Integer object"); } catch (final DecoderException e) { // ignored } } @Test public void testObjectDecodeWithValidParameter() throws Exception { final String original = "Hello World!"; final Object o = Base64.encodeBase64(original.getBytes(CHARSET_UTF8)); final Base64 b64 = new Base64(); final Object oDecoded = b64.decode(o); final byte[] baDecoded = (byte[]) oDecoded; final String dest = new String(baDecoded); assertEquals("dest string does not equal original", original, dest); } @Test public void testObjectEncodeWithInvalidParameter() throws Exception { final Base64 b64 = new Base64(); try { b64.encode("Yadayadayada"); fail("encode(Object) didn't throw an exception when passed a String object"); } catch (final EncoderException e) { // Expected } } @Test public void testObjectEncodeWithValidParameter() throws Exception { final String original = "Hello World!"; final Object origObj = original.getBytes(CHARSET_UTF8); final Base64 b64 = new Base64(); final Object oEncoded = b64.encode(origObj); final byte[] bArray = Base64.decodeBase64((byte[]) oEncoded); final String dest = new String(bArray); assertEquals("dest string does not equal original", original, dest); } @Test public void testObjectEncode() throws Exception { final Base64 b64 = new Base64(); assertEquals("SGVsbG8gV29ybGQ=", new String(b64.encode("Hello World".getBytes(CHARSET_UTF8)))); } @Test public void testPairs() { assertEquals("AAA=", new String(Base64.encodeBase64(new byte[] { 0, 0 }))); for (int i = -128; i <= 127; i++) { final byte test[] = { (byte) i, (byte) i }; assertTrue(Arrays.equals(test, Base64.decodeBase64(Base64.encodeBase64(test)))); } } /** * Tests RFC 2045 section 2.1 CRLF definition. */ @Test public void testRfc2045Section2Dot1CrLfDefinition() { assertTrue(Arrays.equals(new byte[] { 13, 10 }, Base64.CHUNK_SEPARATOR)); } /** * Tests RFC 2045 section 6.8 chuck size definition. */ @Test public void testRfc2045Section6Dot8ChunkSizeDefinition() { assertEquals(76, BaseNCodec.MIME_CHUNK_SIZE); } /** * Tests RFC 1421 section 4.3.2.4 chuck size definition. */ @Test public void testRfc1421Section6Dot8ChunkSizeDefinition() { assertEquals(64, BaseNCodec.PEM_CHUNK_SIZE); } /** * Tests RFC 4648 section 10 test vectors. * <ul> * <li>BASE64("") = ""</li> * <li>BASE64("f") = "Zg=="</li> * <li>BASE64("fo") = "Zm8="</li> * <li>BASE64("foo") = "Zm9v"</li> * <li>BASE64("foob") = "Zm9vYg=="</li> * <li>BASE64("fooba") = "Zm9vYmE="</li> * <li>BASE64("foobar") = "Zm9vYmFy"</li> * </ul> * * @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/ * html/rfc4648</a> */ @Test public void testRfc4648Section10Decode() { assertEquals("", StringUtils.newStringUsAscii(Base64.decodeBase64(""))); assertEquals("f", StringUtils.newStringUsAscii(Base64.decodeBase64("Zg=="))); assertEquals("fo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm8="))); assertEquals("foo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9v"))); assertEquals("foob", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYg=="))); assertEquals("fooba", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmE="))); assertEquals("foobar", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmFy"))); } /** * Tests RFC 4648 section 10 test vectors. * <ul> * <li>BASE64("") = ""</li> * <li>BASE64("f") = "Zg=="</li> * <li>BASE64("fo") = "Zm8="</li> * <li>BASE64("foo") = "Zm9v"</li> * <li>BASE64("foob") = "Zm9vYg=="</li> * <li>BASE64("fooba") = "Zm9vYmE="</li> * <li>BASE64("foobar") = "Zm9vYmFy"</li> * </ul> * * @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/ * html/rfc4648</a> */ @Test public void testRfc4648Section10DecodeWithCrLf() { final String CRLF = StringUtils.newStringUsAscii(Base64.CHUNK_SEPARATOR); assertEquals("", StringUtils.newStringUsAscii(Base64.decodeBase64("" + CRLF))); assertEquals("f", StringUtils.newStringUsAscii(Base64.decodeBase64("Zg==" + CRLF))); assertEquals("fo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm8=" + CRLF))); assertEquals("foo", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9v" + CRLF))); assertEquals("foob", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYg==" + CRLF))); assertEquals("fooba", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmE=" + CRLF))); assertEquals("foobar", StringUtils.newStringUsAscii(Base64.decodeBase64("Zm9vYmFy" + CRLF))); } /** * Tests RFC 4648 section 10 test vectors. * <ul> * <li>BASE64("") = ""</li> * <li>BASE64("f") = "Zg=="</li> * <li>BASE64("fo") = "Zm8="</li> * <li>BASE64("foo") = "Zm9v"</li> * <li>BASE64("foob") = "Zm9vYg=="</li> * <li>BASE64("fooba") = "Zm9vYmE="</li> * <li>BASE64("foobar") = "Zm9vYmFy"</li> * </ul> * * @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/ * html/rfc4648</a> */ @Test public void testRfc4648Section10Encode() { assertEquals("", Base64.encodeBase64String(StringUtils.getBytesUtf8(""))); assertEquals("Zg==", Base64.encodeBase64String(StringUtils.getBytesUtf8("f"))); assertEquals("Zm8=", Base64.encodeBase64String(StringUtils.getBytesUtf8("fo"))); assertEquals("Zm9v", Base64.encodeBase64String(StringUtils.getBytesUtf8("foo"))); assertEquals("Zm9vYg==", Base64.encodeBase64String(StringUtils.getBytesUtf8("foob"))); assertEquals("Zm9vYmE=", Base64.encodeBase64String(StringUtils.getBytesUtf8("fooba"))); assertEquals("Zm9vYmFy", Base64.encodeBase64String(StringUtils.getBytesUtf8("foobar"))); } /** * Tests RFC 4648 section 10 test vectors. * <ul> * <li>BASE64("") = ""</li> * <li>BASE64("f") = "Zg=="</li> * <li>BASE64("fo") = "Zm8="</li> * <li>BASE64("foo") = "Zm9v"</li> * <li>BASE64("foob") = "Zm9vYg=="</li> * <li>BASE64("fooba") = "Zm9vYmE="</li> * <li>BASE64("foobar") = "Zm9vYmFy"</li> * </ul> * * @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/ * html/rfc4648</a> */ @Test public void testRfc4648Section10DecodeEncode() { testDecodeEncode(""); testDecodeEncode("Zg=="); testDecodeEncode("Zm8="); testDecodeEncode("Zm9v"); testDecodeEncode("Zm9vYg=="); testDecodeEncode("Zm9vYmE="); testDecodeEncode("Zm9vYmFy"); } private void testDecodeEncode(final String encodedText) { final String decodedText = StringUtils.newStringUsAscii(Base64.decodeBase64(encodedText)); final String encodedText2 = Base64.encodeBase64String(StringUtils.getBytesUtf8(decodedText)); assertEquals(encodedText, encodedText2); } /** * Tests RFC 4648 section 10 test vectors. * <ul> * <li>BASE64("") = ""</li> * <li>BASE64("f") = "Zg=="</li> * <li>BASE64("fo") = "Zm8="</li> * <li>BASE64("foo") = "Zm9v"</li> * <li>BASE64("foob") = "Zm9vYg=="</li> * <li>BASE64("fooba") = "Zm9vYmE="</li> * <li>BASE64("foobar") = "Zm9vYmFy"</li> * </ul> * * @see <a href="http://tools.ietf.org/html/rfc4648">http://tools.ietf.org/ * html/rfc4648</a> */ @Test public void testRfc4648Section10EncodeDecode() { testEncodeDecode(""); testEncodeDecode("f"); testEncodeDecode("fo"); testEncodeDecode("foo"); testEncodeDecode("foob"); testEncodeDecode("fooba"); testEncodeDecode("foobar"); } private void testEncodeDecode(final String plainText) { final String encodedText = Base64.encodeBase64String(StringUtils.getBytesUtf8(plainText)); final String decodedText = StringUtils.newStringUsAscii(Base64.decodeBase64(encodedText)); assertEquals(plainText, decodedText); } @Test public void testSingletons() { assertEquals("AA==", new String(Base64.encodeBase64(new byte[] { (byte) 0 }))); assertEquals("AQ==", new String(Base64.encodeBase64(new byte[] { (byte) 1 }))); assertEquals("Ag==", new String(Base64.encodeBase64(new byte[] { (byte) 2 }))); assertEquals("Aw==", new String(Base64.encodeBase64(new byte[] { (byte) 3 }))); assertEquals("BA==", new String(Base64.encodeBase64(new byte[] { (byte) 4 }))); assertEquals("BQ==", new String(Base64.encodeBase64(new byte[] { (byte) 5 }))); assertEquals("Bg==", new String(Base64.encodeBase64(new byte[] { (byte) 6 }))); assertEquals("Bw==", new String(Base64.encodeBase64(new byte[] { (byte) 7 }))); assertEquals("CA==", new String(Base64.encodeBase64(new byte[] { (byte) 8 }))); assertEquals("CQ==", new String(Base64.encodeBase64(new byte[] { (byte) 9 }))); assertEquals("Cg==", new String(Base64.encodeBase64(new byte[] { (byte) 10 }))); assertEquals("Cw==", new String(Base64.encodeBase64(new byte[] { (byte) 11 }))); assertEquals("DA==", new String(Base64.encodeBase64(new byte[] { (byte) 12 }))); assertEquals("DQ==", new String(Base64.encodeBase64(new byte[] { (byte) 13 }))); assertEquals("Dg==", new String(Base64.encodeBase64(new byte[] { (byte) 14 }))); assertEquals("Dw==", new String(Base64.encodeBase64(new byte[] { (byte) 15 }))); assertEquals("EA==", new String(Base64.encodeBase64(new byte[] { (byte) 16 }))); assertEquals("EQ==", new String(Base64.encodeBase64(new byte[] { (byte) 17 }))); assertEquals("Eg==", new String(Base64.encodeBase64(new byte[] { (byte) 18 }))); assertEquals("Ew==", new String(Base64.encodeBase64(new byte[] { (byte) 19 }))); assertEquals("FA==", new String(Base64.encodeBase64(new byte[] { (byte) 20 }))); assertEquals("FQ==", new String(Base64.encodeBase64(new byte[] { (byte) 21 }))); assertEquals("Fg==", new String(Base64.encodeBase64(new byte[] { (byte) 22 }))); assertEquals("Fw==", new String(Base64.encodeBase64(new byte[] { (byte) 23 }))); assertEquals("GA==", new String(Base64.encodeBase64(new byte[] { (byte) 24 }))); assertEquals("GQ==", new String(Base64.encodeBase64(new byte[] { (byte) 25 }))); assertEquals("Gg==", new String(Base64.encodeBase64(new byte[] { (byte) 26 }))); assertEquals("Gw==", new String(Base64.encodeBase64(new byte[] { (byte) 27 }))); assertEquals("HA==", new String(Base64.encodeBase64(new byte[] { (byte) 28 }))); assertEquals("HQ==", new String(Base64.encodeBase64(new byte[] { (byte) 29 }))); assertEquals("Hg==", new String(Base64.encodeBase64(new byte[] { (byte) 30 }))); assertEquals("Hw==", new String(Base64.encodeBase64(new byte[] { (byte) 31 }))); assertEquals("IA==", new String(Base64.encodeBase64(new byte[] { (byte) 32 }))); assertEquals("IQ==", new String(Base64.encodeBase64(new byte[] { (byte) 33 }))); assertEquals("Ig==", new String(Base64.encodeBase64(new byte[] { (byte) 34 }))); assertEquals("Iw==", new String(Base64.encodeBase64(new byte[] { (byte) 35 }))); assertEquals("JA==", new String(Base64.encodeBase64(new byte[] { (byte) 36 }))); assertEquals("JQ==", new String(Base64.encodeBase64(new byte[] { (byte) 37 }))); assertEquals("Jg==", new String(Base64.encodeBase64(new byte[] { (byte) 38 }))); assertEquals("Jw==", new String(Base64.encodeBase64(new byte[] { (byte) 39 }))); assertEquals("KA==", new String(Base64.encodeBase64(new byte[] { (byte) 40 }))); assertEquals("KQ==", new String(Base64.encodeBase64(new byte[] { (byte) 41 }))); assertEquals("Kg==", new String(Base64.encodeBase64(new byte[] { (byte) 42 }))); assertEquals("Kw==", new String(Base64.encodeBase64(new byte[] { (byte) 43 }))); assertEquals("LA==", new String(Base64.encodeBase64(new byte[] { (byte) 44 }))); assertEquals("LQ==", new String(Base64.encodeBase64(new byte[] { (byte) 45 }))); assertEquals("Lg==", new String(Base64.encodeBase64(new byte[] { (byte) 46 }))); assertEquals("Lw==", new String(Base64.encodeBase64(new byte[] { (byte) 47 }))); assertEquals("MA==", new String(Base64.encodeBase64(new byte[] { (byte) 48 }))); assertEquals("MQ==", new String(Base64.encodeBase64(new byte[] { (byte) 49 }))); assertEquals("Mg==", new String(Base64.encodeBase64(new byte[] { (byte) 50 }))); assertEquals("Mw==", new String(Base64.encodeBase64(new byte[] { (byte) 51 }))); assertEquals("NA==", new String(Base64.encodeBase64(new byte[] { (byte) 52 }))); assertEquals("NQ==", new String(Base64.encodeBase64(new byte[] { (byte) 53 }))); assertEquals("Ng==", new String(Base64.encodeBase64(new byte[] { (byte) 54 }))); assertEquals("Nw==", new String(Base64.encodeBase64(new byte[] { (byte) 55 }))); assertEquals("OA==", new String(Base64.encodeBase64(new byte[] { (byte) 56 }))); assertEquals("OQ==", new String(Base64.encodeBase64(new byte[] { (byte) 57 }))); assertEquals("Og==", new String(Base64.encodeBase64(new byte[] { (byte) 58 }))); assertEquals("Ow==", new String(Base64.encodeBase64(new byte[] { (byte) 59 }))); assertEquals("PA==", new String(Base64.encodeBase64(new byte[] { (byte) 60 }))); assertEquals("PQ==", new String(Base64.encodeBase64(new byte[] { (byte) 61 }))); assertEquals("Pg==", new String(Base64.encodeBase64(new byte[] { (byte) 62 }))); assertEquals("Pw==", new String(Base64.encodeBase64(new byte[] { (byte) 63 }))); assertEquals("QA==", new String(Base64.encodeBase64(new byte[] { (byte) 64 }))); assertEquals("QQ==", new String(Base64.encodeBase64(new byte[] { (byte) 65 }))); assertEquals("Qg==", new String(Base64.encodeBase64(new byte[] { (byte) 66 }))); assertEquals("Qw==", new String(Base64.encodeBase64(new byte[] { (byte) 67 }))); assertEquals("RA==", new String(Base64.encodeBase64(new byte[] { (byte) 68 }))); assertEquals("RQ==", new String(Base64.encodeBase64(new byte[] { (byte) 69 }))); assertEquals("Rg==", new String(Base64.encodeBase64(new byte[] { (byte) 70 }))); assertEquals("Rw==", new String(Base64.encodeBase64(new byte[] { (byte) 71 }))); assertEquals("SA==", new String(Base64.encodeBase64(new byte[] { (byte) 72 }))); assertEquals("SQ==", new String(Base64.encodeBase64(new byte[] { (byte) 73 }))); assertEquals("Sg==", new String(Base64.encodeBase64(new byte[] { (byte) 74 }))); assertEquals("Sw==", new String(Base64.encodeBase64(new byte[] { (byte) 75 }))); assertEquals("TA==", new String(Base64.encodeBase64(new byte[] { (byte) 76 }))); assertEquals("TQ==", new String(Base64.encodeBase64(new byte[] { (byte) 77 }))); assertEquals("Tg==", new String(Base64.encodeBase64(new byte[] { (byte) 78 }))); assertEquals("Tw==", new String(Base64.encodeBase64(new byte[] { (byte) 79 }))); assertEquals("UA==", new String(Base64.encodeBase64(new byte[] { (byte) 80 }))); assertEquals("UQ==", new String(Base64.encodeBase64(new byte[] { (byte) 81 }))); assertEquals("Ug==", new String(Base64.encodeBase64(new byte[] { (byte) 82 }))); assertEquals("Uw==", new String(Base64.encodeBase64(new byte[] { (byte) 83 }))); assertEquals("VA==", new String(Base64.encodeBase64(new byte[] { (byte) 84 }))); assertEquals("VQ==", new String(Base64.encodeBase64(new byte[] { (byte) 85 }))); assertEquals("Vg==", new String(Base64.encodeBase64(new byte[] { (byte) 86 }))); assertEquals("Vw==", new String(Base64.encodeBase64(new byte[] { (byte) 87 }))); assertEquals("WA==", new String(Base64.encodeBase64(new byte[] { (byte) 88 }))); assertEquals("WQ==", new String(Base64.encodeBase64(new byte[] { (byte) 89 }))); assertEquals("Wg==", new String(Base64.encodeBase64(new byte[] { (byte) 90 }))); assertEquals("Ww==", new String(Base64.encodeBase64(new byte[] { (byte) 91 }))); assertEquals("XA==", new String(Base64.encodeBase64(new byte[] { (byte) 92 }))); assertEquals("XQ==", new String(Base64.encodeBase64(new byte[] { (byte) 93 }))); assertEquals("Xg==", new String(Base64.encodeBase64(new byte[] { (byte) 94 }))); assertEquals("Xw==", new String(Base64.encodeBase64(new byte[] { (byte) 95 }))); assertEquals("YA==", new String(Base64.encodeBase64(new byte[] { (byte) 96 }))); assertEquals("YQ==", new String(Base64.encodeBase64(new byte[] { (byte) 97 }))); assertEquals("Yg==", new String(Base64.encodeBase64(new byte[] { (byte) 98 }))); assertEquals("Yw==", new String(Base64.encodeBase64(new byte[] { (byte) 99 }))); assertEquals("ZA==", new String(Base64.encodeBase64(new byte[] { (byte) 100 }))); assertEquals("ZQ==", new String(Base64.encodeBase64(new byte[] { (byte) 101 }))); assertEquals("Zg==", new String(Base64.encodeBase64(new byte[] { (byte) 102 }))); assertEquals("Zw==", new String(Base64.encodeBase64(new byte[] { (byte) 103 }))); assertEquals("aA==", new String(Base64.encodeBase64(new byte[] { (byte) 104 }))); for (int i = -128; i <= 127; i++) { final byte test[] = { (byte) i }; assertTrue(Arrays.equals(test, Base64.decodeBase64(Base64.encodeBase64(test)))); } } @Test public void testSingletonsChunked() { assertEquals("AA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0 }))); assertEquals("AQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 1 }))); assertEquals("Ag==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 2 }))); assertEquals("Aw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 3 }))); assertEquals("BA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 4 }))); assertEquals("BQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 5 }))); assertEquals("Bg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 6 }))); assertEquals("Bw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 7 }))); assertEquals("CA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 8 }))); assertEquals("CQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 9 }))); assertEquals("Cg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 10 }))); assertEquals("Cw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 11 }))); assertEquals("DA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 12 }))); assertEquals("DQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 13 }))); assertEquals("Dg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 14 }))); assertEquals("Dw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 15 }))); assertEquals("EA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 16 }))); assertEquals("EQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 17 }))); assertEquals("Eg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 18 }))); assertEquals("Ew==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 19 }))); assertEquals("FA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 20 }))); assertEquals("FQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 21 }))); assertEquals("Fg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 22 }))); assertEquals("Fw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 23 }))); assertEquals("GA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 24 }))); assertEquals("GQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 25 }))); assertEquals("Gg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 26 }))); assertEquals("Gw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 27 }))); assertEquals("HA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 28 }))); assertEquals("HQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 29 }))); assertEquals("Hg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 30 }))); assertEquals("Hw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 31 }))); assertEquals("IA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 32 }))); assertEquals("IQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 33 }))); assertEquals("Ig==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 34 }))); assertEquals("Iw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 35 }))); assertEquals("JA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 36 }))); assertEquals("JQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 37 }))); assertEquals("Jg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 38 }))); assertEquals("Jw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 39 }))); assertEquals("KA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 40 }))); assertEquals("KQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 41 }))); assertEquals("Kg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 42 }))); assertEquals("Kw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 43 }))); assertEquals("LA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 44 }))); assertEquals("LQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 45 }))); assertEquals("Lg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 46 }))); assertEquals("Lw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 47 }))); assertEquals("MA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 48 }))); assertEquals("MQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 49 }))); assertEquals("Mg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 50 }))); assertEquals("Mw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 51 }))); assertEquals("NA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 52 }))); assertEquals("NQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 53 }))); assertEquals("Ng==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 54 }))); assertEquals("Nw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 55 }))); assertEquals("OA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 56 }))); assertEquals("OQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 57 }))); assertEquals("Og==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 58 }))); assertEquals("Ow==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 59 }))); assertEquals("PA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 60 }))); assertEquals("PQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 61 }))); assertEquals("Pg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 62 }))); assertEquals("Pw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 63 }))); assertEquals("QA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 64 }))); assertEquals("QQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 65 }))); assertEquals("Qg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 66 }))); assertEquals("Qw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 67 }))); assertEquals("RA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 68 }))); assertEquals("RQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 69 }))); assertEquals("Rg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 70 }))); assertEquals("Rw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 71 }))); assertEquals("SA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 72 }))); assertEquals("SQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 73 }))); assertEquals("Sg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 74 }))); assertEquals("Sw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 75 }))); assertEquals("TA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 76 }))); assertEquals("TQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 77 }))); assertEquals("Tg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 78 }))); assertEquals("Tw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 79 }))); assertEquals("UA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 80 }))); assertEquals("UQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 81 }))); assertEquals("Ug==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 82 }))); assertEquals("Uw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 83 }))); assertEquals("VA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 84 }))); assertEquals("VQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 85 }))); assertEquals("Vg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 86 }))); assertEquals("Vw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 87 }))); assertEquals("WA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 88 }))); assertEquals("WQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 89 }))); assertEquals("Wg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 90 }))); assertEquals("Ww==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 91 }))); assertEquals("XA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 92 }))); assertEquals("XQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 93 }))); assertEquals("Xg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 94 }))); assertEquals("Xw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 95 }))); assertEquals("YA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 96 }))); assertEquals("YQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 97 }))); assertEquals("Yg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 98 }))); assertEquals("Yw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 99 }))); assertEquals("ZA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 100 }))); assertEquals("ZQ==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 101 }))); assertEquals("Zg==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 102 }))); assertEquals("Zw==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 103 }))); assertEquals("aA==\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 104 }))); } @Test public void testTriplets() { assertEquals("AAAA", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 0 }))); assertEquals("AAAB", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 1 }))); assertEquals("AAAC", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 2 }))); assertEquals("AAAD", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 3 }))); assertEquals("AAAE", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 4 }))); assertEquals("AAAF", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 5 }))); assertEquals("AAAG", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 6 }))); assertEquals("AAAH", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 7 }))); assertEquals("AAAI", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 8 }))); assertEquals("AAAJ", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 9 }))); assertEquals("AAAK", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 10 }))); assertEquals("AAAL", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 11 }))); assertEquals("AAAM", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 12 }))); assertEquals("AAAN", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 13 }))); assertEquals("AAAO", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 14 }))); assertEquals("AAAP", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 15 }))); assertEquals("AAAQ", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 16 }))); assertEquals("AAAR", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 17 }))); assertEquals("AAAS", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 18 }))); assertEquals("AAAT", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 19 }))); assertEquals("AAAU", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 20 }))); assertEquals("AAAV", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 21 }))); assertEquals("AAAW", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 22 }))); assertEquals("AAAX", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 23 }))); assertEquals("AAAY", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 24 }))); assertEquals("AAAZ", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 25 }))); assertEquals("AAAa", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 26 }))); assertEquals("AAAb", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 27 }))); assertEquals("AAAc", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 28 }))); assertEquals("AAAd", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 29 }))); assertEquals("AAAe", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 30 }))); assertEquals("AAAf", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 31 }))); assertEquals("AAAg", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 32 }))); assertEquals("AAAh", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 33 }))); assertEquals("AAAi", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 34 }))); assertEquals("AAAj", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 35 }))); assertEquals("AAAk", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 36 }))); assertEquals("AAAl", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 37 }))); assertEquals("AAAm", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 38 }))); assertEquals("AAAn", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 39 }))); assertEquals("AAAo", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 40 }))); assertEquals("AAAp", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 41 }))); assertEquals("AAAq", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 42 }))); assertEquals("AAAr", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 43 }))); assertEquals("AAAs", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 44 }))); assertEquals("AAAt", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 45 }))); assertEquals("AAAu", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 46 }))); assertEquals("AAAv", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 47 }))); assertEquals("AAAw", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 48 }))); assertEquals("AAAx", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 49 }))); assertEquals("AAAy", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 50 }))); assertEquals("AAAz", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 51 }))); assertEquals("AAA0", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 52 }))); assertEquals("AAA1", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 53 }))); assertEquals("AAA2", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 54 }))); assertEquals("AAA3", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 55 }))); assertEquals("AAA4", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 56 }))); assertEquals("AAA5", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 57 }))); assertEquals("AAA6", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 58 }))); assertEquals("AAA7", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 59 }))); assertEquals("AAA8", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 60 }))); assertEquals("AAA9", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 61 }))); assertEquals("AAA+", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 62 }))); assertEquals("AAA/", new String(Base64.encodeBase64(new byte[] { (byte) 0, (byte) 0, (byte) 63 }))); } @Test public void testTripletsChunked() { assertEquals("AAAA\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 0 }))); assertEquals("AAAB\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 1 }))); assertEquals("AAAC\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 2 }))); assertEquals("AAAD\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 3 }))); assertEquals("AAAE\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 4 }))); assertEquals("AAAF\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 5 }))); assertEquals("AAAG\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 6 }))); assertEquals("AAAH\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 7 }))); assertEquals("AAAI\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 8 }))); assertEquals("AAAJ\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 9 }))); assertEquals("AAAK\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 10 }))); assertEquals("AAAL\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 11 }))); assertEquals("AAAM\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 12 }))); assertEquals("AAAN\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 13 }))); assertEquals("AAAO\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 14 }))); assertEquals("AAAP\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 15 }))); assertEquals("AAAQ\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 16 }))); assertEquals("AAAR\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 17 }))); assertEquals("AAAS\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 18 }))); assertEquals("AAAT\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 19 }))); assertEquals("AAAU\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 20 }))); assertEquals("AAAV\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 21 }))); assertEquals("AAAW\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 22 }))); assertEquals("AAAX\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 23 }))); assertEquals("AAAY\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 24 }))); assertEquals("AAAZ\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 25 }))); assertEquals("AAAa\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 26 }))); assertEquals("AAAb\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 27 }))); assertEquals("AAAc\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 28 }))); assertEquals("AAAd\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 29 }))); assertEquals("AAAe\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 30 }))); assertEquals("AAAf\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 31 }))); assertEquals("AAAg\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 32 }))); assertEquals("AAAh\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 33 }))); assertEquals("AAAi\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 34 }))); assertEquals("AAAj\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 35 }))); assertEquals("AAAk\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 36 }))); assertEquals("AAAl\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 37 }))); assertEquals("AAAm\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 38 }))); assertEquals("AAAn\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 39 }))); assertEquals("AAAo\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 40 }))); assertEquals("AAAp\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 41 }))); assertEquals("AAAq\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 42 }))); assertEquals("AAAr\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 43 }))); assertEquals("AAAs\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 44 }))); assertEquals("AAAt\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 45 }))); assertEquals("AAAu\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 46 }))); assertEquals("AAAv\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 47 }))); assertEquals("AAAw\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 48 }))); assertEquals("AAAx\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 49 }))); assertEquals("AAAy\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 50 }))); assertEquals("AAAz\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 51 }))); assertEquals("AAA0\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 52 }))); assertEquals("AAA1\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 53 }))); assertEquals("AAA2\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 54 }))); assertEquals("AAA3\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 55 }))); assertEquals("AAA4\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 56 }))); assertEquals("AAA5\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 57 }))); assertEquals("AAA6\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 58 }))); assertEquals("AAA7\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 59 }))); assertEquals("AAA8\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 60 }))); assertEquals("AAA9\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 61 }))); assertEquals("AAA+\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 62 }))); assertEquals("AAA/\r\n", new String(Base64.encodeBase64Chunked(new byte[] { (byte) 0, (byte) 0, (byte) 63 }))); } /** * Tests url-safe Base64 against random data, sizes 0 to 150. */ @Test public void testUrlSafe() { // test random data of sizes 0 thru 150 for (int i = 0; i <= 150; i++) { final byte[][] randomData = Base64TestData.randomData(i, true); final byte[] encoded = randomData[1]; final byte[] decoded = randomData[0]; final byte[] result = Base64.decodeBase64(encoded); assertTrue("url-safe i=" + i, Arrays.equals(decoded, result)); assertFalse("url-safe i=" + i + " no '='", Base64TestData.bytesContain(encoded, (byte) '=')); assertFalse("url-safe i=" + i + " no '\\'", Base64TestData.bytesContain(encoded, (byte) '\\')); assertFalse("url-safe i=" + i + " no '+'", Base64TestData.bytesContain(encoded, (byte) '+')); } } /** * Base64 encoding of UUID's is a common use-case, especially in URL-SAFE * mode. This test case ends up being the "URL-SAFE" JUnit's. * * @throws DecoderException * if Hex.decode() fails - a serious problem since Hex comes * from our own commons-codec! */ @Test public void testUUID() throws DecoderException { // The 4 UUID's below contains mixtures of + and / to help us test the // URL-SAFE encoding mode. final byte[][] ids = new byte[4][]; // ids[0] was chosen so that it encodes with at least one +. ids[0] = Hex.decodeHex("94ed8d0319e4493399560fb67404d370"); // ids[1] was chosen so that it encodes with both / and +. ids[1] = Hex.decodeHex("2bf7cc2701fe4397b49ebeed5acc7090"); // ids[2] was chosen so that it encodes with at least one /. ids[2] = Hex.decodeHex("64be154b6ffa40258d1a01288e7c31ca"); // ids[3] was chosen so that it encodes with both / and +, with / // right at the beginning. ids[3] = Hex.decodeHex("ff7f8fc01cdb471a8c8b5a9306183fe8"); final byte[][] standard = new byte[4][]; standard[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg+2dATTcA=="); standard[1] = StringUtils.getBytesUtf8("K/fMJwH+Q5e0nr7tWsxwkA=="); standard[2] = StringUtils.getBytesUtf8("ZL4VS2/6QCWNGgEojnwxyg=="); standard[3] = StringUtils.getBytesUtf8("/3+PwBzbRxqMi1qTBhg/6A=="); final byte[][] urlSafe1 = new byte[4][]; // regular padding (two '==' signs). urlSafe1[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg-2dATTcA=="); urlSafe1[1] = StringUtils.getBytesUtf8("K_fMJwH-Q5e0nr7tWsxwkA=="); urlSafe1[2] = StringUtils.getBytesUtf8("ZL4VS2_6QCWNGgEojnwxyg=="); urlSafe1[3] = StringUtils.getBytesUtf8("_3-PwBzbRxqMi1qTBhg_6A=="); final byte[][] urlSafe2 = new byte[4][]; // single padding (only one '=' sign). urlSafe2[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg-2dATTcA="); urlSafe2[1] = StringUtils.getBytesUtf8("K_fMJwH-Q5e0nr7tWsxwkA="); urlSafe2[2] = StringUtils.getBytesUtf8("ZL4VS2_6QCWNGgEojnwxyg="); urlSafe2[3] = StringUtils.getBytesUtf8("_3-PwBzbRxqMi1qTBhg_6A="); final byte[][] urlSafe3 = new byte[4][]; // no padding (no '=' signs). urlSafe3[0] = StringUtils.getBytesUtf8("lO2NAxnkSTOZVg-2dATTcA"); urlSafe3[1] = StringUtils.getBytesUtf8("K_fMJwH-Q5e0nr7tWsxwkA"); urlSafe3[2] = StringUtils.getBytesUtf8("ZL4VS2_6QCWNGgEojnwxyg"); urlSafe3[3] = StringUtils.getBytesUtf8("_3-PwBzbRxqMi1qTBhg_6A"); for (int i = 0; i < 4; i++) { final byte[] encodedStandard = Base64.encodeBase64(ids[i]); final byte[] encodedUrlSafe = Base64.encodeBase64URLSafe(ids[i]); final byte[] decodedStandard = Base64.decodeBase64(standard[i]); final byte[] decodedUrlSafe1 = Base64.decodeBase64(urlSafe1[i]); final byte[] decodedUrlSafe2 = Base64.decodeBase64(urlSafe2[i]); final byte[] decodedUrlSafe3 = Base64.decodeBase64(urlSafe3[i]); // Very important debugging output should anyone // ever need to delve closely into this stuff. // { // System.out.println("reference: [" + Hex.encodeHexString(ids[i]) + "]"); // System.out.println("standard: [" + Hex.encodeHexString(decodedStandard) + "] From: [" // + StringUtils.newStringUtf8(standard[i]) + "]"); // System.out.println("safe1: [" + Hex.encodeHexString(decodedUrlSafe1) + "] From: [" // + StringUtils.newStringUtf8(urlSafe1[i]) + "]"); // System.out.println("safe2: [" + Hex.encodeHexString(decodedUrlSafe2) + "] From: [" // + StringUtils.newStringUtf8(urlSafe2[i]) + "]"); // System.out.println("safe3: [" + Hex.encodeHexString(decodedUrlSafe3) + "] From: [" // + StringUtils.newStringUtf8(urlSafe3[i]) + "]"); // } assertTrue("standard encode uuid", Arrays.equals(encodedStandard, standard[i])); assertTrue("url-safe encode uuid", Arrays.equals(encodedUrlSafe, urlSafe3[i])); assertTrue("standard decode uuid", Arrays.equals(decodedStandard, ids[i])); assertTrue("url-safe1 decode uuid", Arrays.equals(decodedUrlSafe1, ids[i])); assertTrue("url-safe2 decode uuid", Arrays.equals(decodedUrlSafe2, ids[i])); assertTrue("url-safe3 decode uuid", Arrays.equals(decodedUrlSafe3, ids[i])); } } @Test public void testByteToStringVariations() throws DecoderException { final Base64 base64 = new Base64(0); final byte[] b1 = StringUtils.getBytesUtf8("Hello World"); final byte[] b2 = new byte[0]; final byte[] b3 = null; final byte[] b4 = Hex.decodeHex("2bf7cc2701fe4397b49ebeed5acc7090"); // for // url-safe // tests assertEquals("byteToString Hello World", "SGVsbG8gV29ybGQ=", base64.encodeToString(b1)); assertEquals("byteToString static Hello World", "SGVsbG8gV29ybGQ=", Base64.encodeBase64String(b1)); assertEquals("byteToString \"\"", "", base64.encodeToString(b2)); assertEquals("byteToString static \"\"", "", Base64.encodeBase64String(b2)); assertEquals("byteToString null", null, base64.encodeToString(b3)); assertEquals("byteToString static null", null, Base64.encodeBase64String(b3)); assertEquals("byteToString UUID", "K/fMJwH+Q5e0nr7tWsxwkA==", base64.encodeToString(b4)); assertEquals("byteToString static UUID", "K/fMJwH+Q5e0nr7tWsxwkA==", Base64.encodeBase64String(b4)); assertEquals("byteToString static-url-safe UUID", "K_fMJwH-Q5e0nr7tWsxwkA", Base64.encodeBase64URLSafeString(b4)); } @Test public void testStringToByteVariations() throws DecoderException { final Base64 base64 = new Base64(); final String s1 = "SGVsbG8gV29ybGQ=\r\n"; final String s2 = ""; final String s3 = null; final String s4a = "K/fMJwH+Q5e0nr7tWsxwkA==\r\n"; final String s4b = "K_fMJwH-Q5e0nr7tWsxwkA"; final byte[] b4 = Hex.decodeHex("2bf7cc2701fe4397b49ebeed5acc7090"); // for // url-safe // tests assertEquals("StringToByte Hello World", "Hello World", StringUtils.newStringUtf8(base64.decode(s1))); assertEquals("StringToByte Hello World", "Hello World", StringUtils.newStringUtf8((byte[]) base64.decode((Object) s1))); assertEquals("StringToByte static Hello World", "Hello World", StringUtils.newStringUtf8(Base64.decodeBase64(s1))); assertEquals("StringToByte \"\"", "", StringUtils.newStringUtf8(base64.decode(s2))); assertEquals("StringToByte static \"\"", "", StringUtils.newStringUtf8(Base64.decodeBase64(s2))); assertEquals("StringToByte null", null, StringUtils.newStringUtf8(base64.decode(s3))); assertEquals("StringToByte static null", null, StringUtils.newStringUtf8(Base64.decodeBase64(s3))); assertTrue("StringToByte UUID", Arrays.equals(b4, base64.decode(s4b))); assertTrue("StringToByte static UUID", Arrays.equals(b4, Base64.decodeBase64(s4a))); assertTrue("StringToByte static-url-safe UUID", Arrays.equals(b4, Base64.decodeBase64(s4b))); } private String toString(final byte[] data) { final StringBuilder buf = new StringBuilder(); for (int i = 0; i < data.length; i++) { buf.append(data[i]); if (i != data.length - 1) { buf.append(","); } } return buf.toString(); } /** * Tests a lineSeparator much bigger than DEFAULT_BUFFER_SIZE. * * @see "<a href='http://mail-archives.apache.org/mod_mbox/commons-dev/201202.mbox/%3C4F3C85D7.5060706@snafu.de%3E'>dev@commons.apache.org</a>" */ @Test @Ignore public void testHugeLineSeparator() { final int BaseNCodec_DEFAULT_BUFFER_SIZE = 8192; final int Base64_BYTES_PER_ENCODED_BLOCK = 4; final byte[] baLineSeparator = new byte[BaseNCodec_DEFAULT_BUFFER_SIZE * 4 - 3]; final Base64 b64 = new Base64(Base64_BYTES_PER_ENCODED_BLOCK, baLineSeparator); final String strOriginal = "Hello World"; final String strDecoded = new String(b64.decode(b64.encode(StringUtils.getBytesUtf8(strOriginal)))); assertEquals("testDEFAULT_BUFFER_SIZE", strOriginal, strDecoded); } }
[ { "be_test_class_file": "org/apache/commons/codec/binary/Base64.java", "be_test_class_name": "org.apache.commons.codec.binary.Base64", "be_test_function_name": "decode", "be_test_function_signature": "([BIILorg/apache/commons/codec/binary/BaseNCodec$Context;)V", "line_numbers": [ "431", "432", "434", "435", "437", "438", "439", "440", "442", "443", "445", "446", "447", "448", "449", "450", "451", "452", "453", "462", "463", "467", "471", "473", "474", "475", "477", "478", "479", "480", "482", "485" ], "method_line_rate": 0.9375 }, { "be_test_class_file": "org/apache/commons/codec/binary/Base64.java", "be_test_class_name": "org.apache.commons.codec.binary.Base64", "be_test_function_name": "decodeBase64", "be_test_function_signature": "(Ljava/lang/String;)[B", "line_numbers": [ "693" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/codec/binary/Base64.java", "be_test_class_name": "org.apache.commons.codec.binary.Base64", "be_test_function_name": "isInAlphabet", "be_test_function_signature": "(B)Z", "line_numbers": [ "782" ], "method_line_rate": 1 } ]
public class ChartPanelTests extends TestCase implements ChartChangeListener, ChartMouseListener
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()); }
// 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_zoomInDomain` for the `ChartPanel` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Checks that a call to the zoomInDomain() 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();
249
test2502355_zoomInDomain
```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_zoomInDomain` 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 zoomInDomain() method, for a plot with more * than one domain axis, generates just one ChartChangeEvent. */
238
// 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_zoomInDomain` for the `ChartPanel` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * 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() {
/** * Checks that a call to the zoomInDomain() 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_zoomInDomain` 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 zoomInDomain() method, for a plot with more * than one domain axis, generates just one ChartChangeEvent. */ public void test2502355_zoomInDomain() { ```
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();
235e41814ee0b5bf9259a5f39af6841f636cc3cc01cd7650b84b0d80d586df88
[ "org.jfree.chart.junit.ChartPanelTests::test2502355_zoomInDomain" ]
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_zoomInDomain()
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": "zoomInDomain", "be_test_function_signature": "(DD)V", "line_numbers": [ "2115", "2116", "2120", "2121", "2122", "2123", "2126", "2128" ], "method_line_rate": 1 } ]
@SuppressWarnings("boxing") public class OpenIntToDoubleHashMapTest
@Test public void testPutKeysWithCollision2() { OpenIntToDoubleHashMap map = new OpenIntToDoubleHashMap(); int key1 = 837989881; double value1 = 1.0; map.put(key1, value1); int key2 = 476463321; map.put(key2, value1); Assert.assertEquals(2, map.size()); Assert.assertTrue(Precision.equals(value1, map.get(key2), 1)); map.remove(key1); double value2 = 2.0; map.put(key2, value2); Assert.assertEquals(1, map.size()); Assert.assertTrue(Precision.equals(value2, map.get(key2), 1)); }
// // Abstract Java Tested Class // package org.apache.commons.math3.util; // // import java.io.IOException; // import java.io.ObjectInputStream; // import java.io.Serializable; // import java.util.ConcurrentModificationException; // import java.util.NoSuchElementException; // // // // public class OpenIntToDoubleHashMap implements Serializable { // protected static final byte FREE = 0; // protected static final byte FULL = 1; // protected static final byte REMOVED = 2; // private static final long serialVersionUID = -3646337053166149105L; // private static final float LOAD_FACTOR = 0.5f; // private static final int DEFAULT_EXPECTED_SIZE = 16; // private static final int RESIZE_MULTIPLIER = 2; // private static final int PERTURB_SHIFT = 5; // private int[] keys; // private double[] values; // private byte[] states; // private final double missingEntries; // private int size; // private int mask; // private transient int count; // // public OpenIntToDoubleHashMap(); // public OpenIntToDoubleHashMap(final double missingEntries); // public OpenIntToDoubleHashMap(final int expectedSize); // public OpenIntToDoubleHashMap(final int expectedSize, // final double missingEntries); // public OpenIntToDoubleHashMap(final OpenIntToDoubleHashMap source); // private static int computeCapacity(final int expectedSize); // private static int nextPowerOfTwo(final int i); // public double get(final int key); // public boolean containsKey(final int key); // public Iterator iterator(); // private static int perturb(final int hash); // private int findInsertionIndex(final int key); // private static int findInsertionIndex(final int[] keys, final byte[] states, // final int key, final int mask); // private static int probe(final int perturb, final int j); // private static int changeIndexSign(final int index); // public int size(); // public double remove(final int key); // private boolean containsKey(final int key, final int index); // private double doRemove(int index); // public double put(final int key, final double value); // private void growTable(); // private boolean shouldGrowTable(); // private static int hashOf(final int key); // private void readObject(final ObjectInputStream stream) // throws IOException, ClassNotFoundException; // private Iterator(); // public boolean hasNext(); // public int key() // throws ConcurrentModificationException, NoSuchElementException; // public double value() // throws ConcurrentModificationException, NoSuchElementException; // public void advance() // throws ConcurrentModificationException, NoSuchElementException; // } // // // Abstract Java Test Class // package org.apache.commons.math3.util; // // import java.util.ConcurrentModificationException; // import java.util.HashMap; // import java.util.HashSet; // import java.util.Map; // import java.util.NoSuchElementException; // import java.util.Random; // import java.util.Set; // import org.junit.Assert; // import org.junit.Before; // import org.junit.Test; // // // // @SuppressWarnings("boxing") // public class OpenIntToDoubleHashMapTest { // private Map<Integer, Double> javaMap = new HashMap<Integer, Double>(); // // @Before // public void setUp() throws Exception; // private Map<Integer, Double> generate(); // private OpenIntToDoubleHashMap createFromJavaMap(); // @Test // public void testPutAndGetWith0ExpectedSize(); // @Test // public void testPutAndGetWithExpectedSize(); // @Test // public void testPutAndGet(); // private void assertPutAndGet(OpenIntToDoubleHashMap map); // private void assertPutAndGet(OpenIntToDoubleHashMap map, int mapSize, // Set<Integer> keysInMap); // @Test // public void testPutAbsentOnExisting(); // @Test // public void testPutOnExisting(); // @Test // public void testGetAbsent(); // @Test // public void testGetFromEmpty(); // @Test // public void testRemove(); // @Test // public void testRemove2(); // @Test // public void testRemoveFromEmpty(); // @Test // public void testRemoveAbsent(); // private Map<Integer, Double> generateAbsent(); // @Test // public void testCopy(); // @Test // public void testContainsKey(); // @Test // public void testIterator(); // @Test // public void testConcurrentModification(); // @Test // public void testPutKeysWithCollisions(); // @Test // public void testPutKeysWithCollision2(); // } // You are a professional Java test case writer, please create a test case named `testPutKeysWithCollision2` for the `OpenIntToDoubleHashMap` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Similar to testPutKeysWithCollisions() but exercises the codepaths in a slightly * different manner. */
src/test/java/org/apache/commons/math3/util/OpenIntToDoubleHashMapTest.java
package org.apache.commons.math3.util; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.ConcurrentModificationException; import java.util.NoSuchElementException;
public OpenIntToDoubleHashMap(); public OpenIntToDoubleHashMap(final double missingEntries); public OpenIntToDoubleHashMap(final int expectedSize); public OpenIntToDoubleHashMap(final int expectedSize, final double missingEntries); public OpenIntToDoubleHashMap(final OpenIntToDoubleHashMap source); private static int computeCapacity(final int expectedSize); private static int nextPowerOfTwo(final int i); public double get(final int key); public boolean containsKey(final int key); public Iterator iterator(); private static int perturb(final int hash); private int findInsertionIndex(final int key); private static int findInsertionIndex(final int[] keys, final byte[] states, final int key, final int mask); private static int probe(final int perturb, final int j); private static int changeIndexSign(final int index); public int size(); public double remove(final int key); private boolean containsKey(final int key, final int index); private double doRemove(int index); public double put(final int key, final double value); private void growTable(); private boolean shouldGrowTable(); private static int hashOf(final int key); private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException; private Iterator(); public boolean hasNext(); public int key() throws ConcurrentModificationException, NoSuchElementException; public double value() throws ConcurrentModificationException, NoSuchElementException; public void advance() throws ConcurrentModificationException, NoSuchElementException;
322
testPutKeysWithCollision2
```java // Abstract Java Tested Class package org.apache.commons.math3.util; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.ConcurrentModificationException; import java.util.NoSuchElementException; public class OpenIntToDoubleHashMap implements Serializable { protected static final byte FREE = 0; protected static final byte FULL = 1; protected static final byte REMOVED = 2; private static final long serialVersionUID = -3646337053166149105L; private static final float LOAD_FACTOR = 0.5f; private static final int DEFAULT_EXPECTED_SIZE = 16; private static final int RESIZE_MULTIPLIER = 2; private static final int PERTURB_SHIFT = 5; private int[] keys; private double[] values; private byte[] states; private final double missingEntries; private int size; private int mask; private transient int count; public OpenIntToDoubleHashMap(); public OpenIntToDoubleHashMap(final double missingEntries); public OpenIntToDoubleHashMap(final int expectedSize); public OpenIntToDoubleHashMap(final int expectedSize, final double missingEntries); public OpenIntToDoubleHashMap(final OpenIntToDoubleHashMap source); private static int computeCapacity(final int expectedSize); private static int nextPowerOfTwo(final int i); public double get(final int key); public boolean containsKey(final int key); public Iterator iterator(); private static int perturb(final int hash); private int findInsertionIndex(final int key); private static int findInsertionIndex(final int[] keys, final byte[] states, final int key, final int mask); private static int probe(final int perturb, final int j); private static int changeIndexSign(final int index); public int size(); public double remove(final int key); private boolean containsKey(final int key, final int index); private double doRemove(int index); public double put(final int key, final double value); private void growTable(); private boolean shouldGrowTable(); private static int hashOf(final int key); private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException; private Iterator(); public boolean hasNext(); public int key() throws ConcurrentModificationException, NoSuchElementException; public double value() throws ConcurrentModificationException, NoSuchElementException; public void advance() throws ConcurrentModificationException, NoSuchElementException; } // Abstract Java Test Class package org.apache.commons.math3.util; import java.util.ConcurrentModificationException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.NoSuchElementException; import java.util.Random; import java.util.Set; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @SuppressWarnings("boxing") public class OpenIntToDoubleHashMapTest { private Map<Integer, Double> javaMap = new HashMap<Integer, Double>(); @Before public void setUp() throws Exception; private Map<Integer, Double> generate(); private OpenIntToDoubleHashMap createFromJavaMap(); @Test public void testPutAndGetWith0ExpectedSize(); @Test public void testPutAndGetWithExpectedSize(); @Test public void testPutAndGet(); private void assertPutAndGet(OpenIntToDoubleHashMap map); private void assertPutAndGet(OpenIntToDoubleHashMap map, int mapSize, Set<Integer> keysInMap); @Test public void testPutAbsentOnExisting(); @Test public void testPutOnExisting(); @Test public void testGetAbsent(); @Test public void testGetFromEmpty(); @Test public void testRemove(); @Test public void testRemove2(); @Test public void testRemoveFromEmpty(); @Test public void testRemoveAbsent(); private Map<Integer, Double> generateAbsent(); @Test public void testCopy(); @Test public void testContainsKey(); @Test public void testIterator(); @Test public void testConcurrentModification(); @Test public void testPutKeysWithCollisions(); @Test public void testPutKeysWithCollision2(); } ``` You are a professional Java test case writer, please create a test case named `testPutKeysWithCollision2` for the `OpenIntToDoubleHashMap` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Similar to testPutKeysWithCollisions() but exercises the codepaths in a slightly * different manner. */
306
// // Abstract Java Tested Class // package org.apache.commons.math3.util; // // import java.io.IOException; // import java.io.ObjectInputStream; // import java.io.Serializable; // import java.util.ConcurrentModificationException; // import java.util.NoSuchElementException; // // // // public class OpenIntToDoubleHashMap implements Serializable { // protected static final byte FREE = 0; // protected static final byte FULL = 1; // protected static final byte REMOVED = 2; // private static final long serialVersionUID = -3646337053166149105L; // private static final float LOAD_FACTOR = 0.5f; // private static final int DEFAULT_EXPECTED_SIZE = 16; // private static final int RESIZE_MULTIPLIER = 2; // private static final int PERTURB_SHIFT = 5; // private int[] keys; // private double[] values; // private byte[] states; // private final double missingEntries; // private int size; // private int mask; // private transient int count; // // public OpenIntToDoubleHashMap(); // public OpenIntToDoubleHashMap(final double missingEntries); // public OpenIntToDoubleHashMap(final int expectedSize); // public OpenIntToDoubleHashMap(final int expectedSize, // final double missingEntries); // public OpenIntToDoubleHashMap(final OpenIntToDoubleHashMap source); // private static int computeCapacity(final int expectedSize); // private static int nextPowerOfTwo(final int i); // public double get(final int key); // public boolean containsKey(final int key); // public Iterator iterator(); // private static int perturb(final int hash); // private int findInsertionIndex(final int key); // private static int findInsertionIndex(final int[] keys, final byte[] states, // final int key, final int mask); // private static int probe(final int perturb, final int j); // private static int changeIndexSign(final int index); // public int size(); // public double remove(final int key); // private boolean containsKey(final int key, final int index); // private double doRemove(int index); // public double put(final int key, final double value); // private void growTable(); // private boolean shouldGrowTable(); // private static int hashOf(final int key); // private void readObject(final ObjectInputStream stream) // throws IOException, ClassNotFoundException; // private Iterator(); // public boolean hasNext(); // public int key() // throws ConcurrentModificationException, NoSuchElementException; // public double value() // throws ConcurrentModificationException, NoSuchElementException; // public void advance() // throws ConcurrentModificationException, NoSuchElementException; // } // // // Abstract Java Test Class // package org.apache.commons.math3.util; // // import java.util.ConcurrentModificationException; // import java.util.HashMap; // import java.util.HashSet; // import java.util.Map; // import java.util.NoSuchElementException; // import java.util.Random; // import java.util.Set; // import org.junit.Assert; // import org.junit.Before; // import org.junit.Test; // // // // @SuppressWarnings("boxing") // public class OpenIntToDoubleHashMapTest { // private Map<Integer, Double> javaMap = new HashMap<Integer, Double>(); // // @Before // public void setUp() throws Exception; // private Map<Integer, Double> generate(); // private OpenIntToDoubleHashMap createFromJavaMap(); // @Test // public void testPutAndGetWith0ExpectedSize(); // @Test // public void testPutAndGetWithExpectedSize(); // @Test // public void testPutAndGet(); // private void assertPutAndGet(OpenIntToDoubleHashMap map); // private void assertPutAndGet(OpenIntToDoubleHashMap map, int mapSize, // Set<Integer> keysInMap); // @Test // public void testPutAbsentOnExisting(); // @Test // public void testPutOnExisting(); // @Test // public void testGetAbsent(); // @Test // public void testGetFromEmpty(); // @Test // public void testRemove(); // @Test // public void testRemove2(); // @Test // public void testRemoveFromEmpty(); // @Test // public void testRemoveAbsent(); // private Map<Integer, Double> generateAbsent(); // @Test // public void testCopy(); // @Test // public void testContainsKey(); // @Test // public void testIterator(); // @Test // public void testConcurrentModification(); // @Test // public void testPutKeysWithCollisions(); // @Test // public void testPutKeysWithCollision2(); // } // You are a professional Java test case writer, please create a test case named `testPutKeysWithCollision2` for the `OpenIntToDoubleHashMap` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Similar to testPutKeysWithCollisions() but exercises the codepaths in a slightly * different manner. */ @Test public void testPutKeysWithCollision2() {
/** * Similar to testPutKeysWithCollisions() but exercises the codepaths in a slightly * different manner. */
1
org.apache.commons.math3.util.OpenIntToDoubleHashMap
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.math3.util; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.ConcurrentModificationException; import java.util.NoSuchElementException; public class OpenIntToDoubleHashMap implements Serializable { protected static final byte FREE = 0; protected static final byte FULL = 1; protected static final byte REMOVED = 2; private static final long serialVersionUID = -3646337053166149105L; private static final float LOAD_FACTOR = 0.5f; private static final int DEFAULT_EXPECTED_SIZE = 16; private static final int RESIZE_MULTIPLIER = 2; private static final int PERTURB_SHIFT = 5; private int[] keys; private double[] values; private byte[] states; private final double missingEntries; private int size; private int mask; private transient int count; public OpenIntToDoubleHashMap(); public OpenIntToDoubleHashMap(final double missingEntries); public OpenIntToDoubleHashMap(final int expectedSize); public OpenIntToDoubleHashMap(final int expectedSize, final double missingEntries); public OpenIntToDoubleHashMap(final OpenIntToDoubleHashMap source); private static int computeCapacity(final int expectedSize); private static int nextPowerOfTwo(final int i); public double get(final int key); public boolean containsKey(final int key); public Iterator iterator(); private static int perturb(final int hash); private int findInsertionIndex(final int key); private static int findInsertionIndex(final int[] keys, final byte[] states, final int key, final int mask); private static int probe(final int perturb, final int j); private static int changeIndexSign(final int index); public int size(); public double remove(final int key); private boolean containsKey(final int key, final int index); private double doRemove(int index); public double put(final int key, final double value); private void growTable(); private boolean shouldGrowTable(); private static int hashOf(final int key); private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException; private Iterator(); public boolean hasNext(); public int key() throws ConcurrentModificationException, NoSuchElementException; public double value() throws ConcurrentModificationException, NoSuchElementException; public void advance() throws ConcurrentModificationException, NoSuchElementException; } // Abstract Java Test Class package org.apache.commons.math3.util; import java.util.ConcurrentModificationException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.NoSuchElementException; import java.util.Random; import java.util.Set; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @SuppressWarnings("boxing") public class OpenIntToDoubleHashMapTest { private Map<Integer, Double> javaMap = new HashMap<Integer, Double>(); @Before public void setUp() throws Exception; private Map<Integer, Double> generate(); private OpenIntToDoubleHashMap createFromJavaMap(); @Test public void testPutAndGetWith0ExpectedSize(); @Test public void testPutAndGetWithExpectedSize(); @Test public void testPutAndGet(); private void assertPutAndGet(OpenIntToDoubleHashMap map); private void assertPutAndGet(OpenIntToDoubleHashMap map, int mapSize, Set<Integer> keysInMap); @Test public void testPutAbsentOnExisting(); @Test public void testPutOnExisting(); @Test public void testGetAbsent(); @Test public void testGetFromEmpty(); @Test public void testRemove(); @Test public void testRemove2(); @Test public void testRemoveFromEmpty(); @Test public void testRemoveAbsent(); private Map<Integer, Double> generateAbsent(); @Test public void testCopy(); @Test public void testContainsKey(); @Test public void testIterator(); @Test public void testConcurrentModification(); @Test public void testPutKeysWithCollisions(); @Test public void testPutKeysWithCollision2(); } ``` You are a professional Java test case writer, please create a test case named `testPutKeysWithCollision2` for the `OpenIntToDoubleHashMap` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Similar to testPutKeysWithCollisions() but exercises the codepaths in a slightly * different manner. */ @Test public void testPutKeysWithCollision2() { ```
public class OpenIntToDoubleHashMap implements Serializable
package org.apache.commons.math3.util; import java.util.ConcurrentModificationException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.NoSuchElementException; import java.util.Random; import java.util.Set; import org.junit.Assert; import org.junit.Before; import org.junit.Test;
@Before public void setUp() throws Exception; private Map<Integer, Double> generate(); private OpenIntToDoubleHashMap createFromJavaMap(); @Test public void testPutAndGetWith0ExpectedSize(); @Test public void testPutAndGetWithExpectedSize(); @Test public void testPutAndGet(); private void assertPutAndGet(OpenIntToDoubleHashMap map); private void assertPutAndGet(OpenIntToDoubleHashMap map, int mapSize, Set<Integer> keysInMap); @Test public void testPutAbsentOnExisting(); @Test public void testPutOnExisting(); @Test public void testGetAbsent(); @Test public void testGetFromEmpty(); @Test public void testRemove(); @Test public void testRemove2(); @Test public void testRemoveFromEmpty(); @Test public void testRemoveAbsent(); private Map<Integer, Double> generateAbsent(); @Test public void testCopy(); @Test public void testContainsKey(); @Test public void testIterator(); @Test public void testConcurrentModification(); @Test public void testPutKeysWithCollisions(); @Test public void testPutKeysWithCollision2();
23c0372c3aac6bc58c044096c6c7f9a7c849bbde32498ab8d95778db55f63af0
[ "org.apache.commons.math3.util.OpenIntToDoubleHashMapTest::testPutKeysWithCollision2" ]
protected static final byte FREE = 0; protected static final byte FULL = 1; protected static final byte REMOVED = 2; private static final long serialVersionUID = -3646337053166149105L; private static final float LOAD_FACTOR = 0.5f; private static final int DEFAULT_EXPECTED_SIZE = 16; private static final int RESIZE_MULTIPLIER = 2; private static final int PERTURB_SHIFT = 5; private int[] keys; private double[] values; private byte[] states; private final double missingEntries; private int size; private int mask; private transient int count;
@Test public void testPutKeysWithCollision2()
private Map<Integer, Double> javaMap = new HashMap<Integer, Double>();
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.util; import java.util.ConcurrentModificationException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.NoSuchElementException; import java.util.Random; import java.util.Set; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Test cases for the {@link OpenIntToDoubleHashMap}. */ @SuppressWarnings("boxing") public class OpenIntToDoubleHashMapTest { private Map<Integer, Double> javaMap = new HashMap<Integer, Double>(); @Before public void setUp() throws Exception { javaMap.put(50, 100.0); javaMap.put(75, 75.0); javaMap.put(25, 500.0); javaMap.put(Integer.MAX_VALUE, Double.MAX_VALUE); javaMap.put(0, -1.0); javaMap.put(1, 0.0); javaMap.put(33, -0.1); javaMap.put(23234234, -242343.0); javaMap.put(23321, Double.MIN_VALUE); javaMap.put(-4444, 332.0); javaMap.put(-1, -2323.0); javaMap.put(Integer.MIN_VALUE, 44.0); /* Add a few more to cause the table to rehash */ javaMap.putAll(generate()); } private Map<Integer, Double> generate() { Map<Integer, Double> map = new HashMap<Integer, Double>(); Random r = new Random(); for (int i = 0; i < 2000; ++i) map.put(r.nextInt(), r.nextDouble()); return map; } private OpenIntToDoubleHashMap createFromJavaMap() { OpenIntToDoubleHashMap map = new OpenIntToDoubleHashMap(); for (Map.Entry<Integer, Double> mapEntry : javaMap.entrySet()) { map.put(mapEntry.getKey(), mapEntry.getValue()); } return map; } @Test public void testPutAndGetWith0ExpectedSize() { OpenIntToDoubleHashMap map = new OpenIntToDoubleHashMap(0); assertPutAndGet(map); } @Test public void testPutAndGetWithExpectedSize() { OpenIntToDoubleHashMap map = new OpenIntToDoubleHashMap(500); assertPutAndGet(map); } @Test public void testPutAndGet() { OpenIntToDoubleHashMap map = new OpenIntToDoubleHashMap(); assertPutAndGet(map); } private void assertPutAndGet(OpenIntToDoubleHashMap map) { assertPutAndGet(map, 0, new HashSet<Integer>()); } private void assertPutAndGet(OpenIntToDoubleHashMap map, int mapSize, Set<Integer> keysInMap) { Assert.assertEquals(mapSize, map.size()); for (Map.Entry<Integer, Double> mapEntry : javaMap.entrySet()) { map.put(mapEntry.getKey(), mapEntry.getValue()); if (!keysInMap.contains(mapEntry.getKey())) ++mapSize; Assert.assertEquals(mapSize, map.size()); Assert.assertTrue(Precision.equals(mapEntry.getValue(), map.get(mapEntry.getKey()), 1)); } } @Test public void testPutAbsentOnExisting() { OpenIntToDoubleHashMap map = createFromJavaMap(); int size = javaMap.size(); for (Map.Entry<Integer, Double> mapEntry : generateAbsent().entrySet()) { map.put(mapEntry.getKey(), mapEntry.getValue()); Assert.assertEquals(++size, map.size()); Assert.assertTrue(Precision.equals(mapEntry.getValue(), map.get(mapEntry.getKey()), 1)); } } @Test public void testPutOnExisting() { OpenIntToDoubleHashMap map = createFromJavaMap(); for (Map.Entry<Integer, Double> mapEntry : javaMap.entrySet()) { map.put(mapEntry.getKey(), mapEntry.getValue()); Assert.assertEquals(javaMap.size(), map.size()); Assert.assertTrue(Precision.equals(mapEntry.getValue(), map.get(mapEntry.getKey()), 1)); } } @Test public void testGetAbsent() { Map<Integer, Double> generated = generateAbsent(); OpenIntToDoubleHashMap map = createFromJavaMap(); for (Map.Entry<Integer, Double> mapEntry : generated.entrySet()) Assert.assertTrue(Double.isNaN(map.get(mapEntry.getKey()))); } @Test public void testGetFromEmpty() { OpenIntToDoubleHashMap map = new OpenIntToDoubleHashMap(); Assert.assertTrue(Double.isNaN(map.get(5))); Assert.assertTrue(Double.isNaN(map.get(0))); Assert.assertTrue(Double.isNaN(map.get(50))); } @Test public void testRemove() { OpenIntToDoubleHashMap map = createFromJavaMap(); int mapSize = javaMap.size(); Assert.assertEquals(mapSize, map.size()); for (Map.Entry<Integer, Double> mapEntry : javaMap.entrySet()) { map.remove(mapEntry.getKey()); Assert.assertEquals(--mapSize, map.size()); Assert.assertTrue(Double.isNaN(map.get(mapEntry.getKey()))); } /* Ensure that put and get still work correctly after removals */ assertPutAndGet(map); } /* This time only remove some entries */ @Test public void testRemove2() { OpenIntToDoubleHashMap map = createFromJavaMap(); int mapSize = javaMap.size(); int count = 0; Set<Integer> keysInMap = new HashSet<Integer>(javaMap.keySet()); for (Map.Entry<Integer, Double> mapEntry : javaMap.entrySet()) { keysInMap.remove(mapEntry.getKey()); map.remove(mapEntry.getKey()); Assert.assertEquals(--mapSize, map.size()); Assert.assertTrue(Double.isNaN(map.get(mapEntry.getKey()))); if (count++ > 5) break; } /* Ensure that put and get still work correctly after removals */ assertPutAndGet(map, mapSize, keysInMap); } @Test public void testRemoveFromEmpty() { OpenIntToDoubleHashMap map = new OpenIntToDoubleHashMap(); Assert.assertTrue(Double.isNaN(map.remove(50))); } @Test public void testRemoveAbsent() { Map<Integer, Double> generated = generateAbsent(); OpenIntToDoubleHashMap map = createFromJavaMap(); int mapSize = map.size(); for (Map.Entry<Integer, Double> mapEntry : generated.entrySet()) { map.remove(mapEntry.getKey()); Assert.assertEquals(mapSize, map.size()); Assert.assertTrue(Double.isNaN(map.get(mapEntry.getKey()))); } } /** * Returns a map with at least 100 elements where each element is absent from javaMap. */ private Map<Integer, Double> generateAbsent() { Map<Integer, Double> generated = new HashMap<Integer, Double>(); do { generated.putAll(generate()); for (Integer key : javaMap.keySet()) generated.remove(key); } while (generated.size() < 100); return generated; } @Test public void testCopy() { OpenIntToDoubleHashMap copy = new OpenIntToDoubleHashMap(createFromJavaMap()); Assert.assertEquals(javaMap.size(), copy.size()); for (Map.Entry<Integer, Double> mapEntry : javaMap.entrySet()) Assert.assertTrue(Precision.equals(mapEntry.getValue(), copy.get(mapEntry.getKey()), 1)); } @Test public void testContainsKey() { OpenIntToDoubleHashMap map = createFromJavaMap(); for (Map.Entry<Integer, Double> mapEntry : javaMap.entrySet()) { Assert.assertTrue(map.containsKey(mapEntry.getKey())); } for (Map.Entry<Integer, Double> mapEntry : generateAbsent().entrySet()) { Assert.assertFalse(map.containsKey(mapEntry.getKey())); } for (Map.Entry<Integer, Double> mapEntry : javaMap.entrySet()) { int key = mapEntry.getKey(); Assert.assertTrue(map.containsKey(key)); map.remove(key); Assert.assertFalse(map.containsKey(key)); } } @Test public void testIterator() { OpenIntToDoubleHashMap map = createFromJavaMap(); OpenIntToDoubleHashMap.Iterator iterator = map.iterator(); for (int i = 0; i < map.size(); ++i) { Assert.assertTrue(iterator.hasNext()); iterator.advance(); int key = iterator.key(); Assert.assertTrue(map.containsKey(key)); Assert.assertEquals(javaMap.get(key), map.get(key), 0); Assert.assertEquals(javaMap.get(key), iterator.value(), 0); Assert.assertTrue(javaMap.containsKey(key)); } Assert.assertFalse(iterator.hasNext()); try { iterator.advance(); Assert.fail("an exception should have been thrown"); } catch (NoSuchElementException nsee) { // expected } } @Test public void testConcurrentModification() { OpenIntToDoubleHashMap map = createFromJavaMap(); OpenIntToDoubleHashMap.Iterator iterator = map.iterator(); map.put(3, 3); try { iterator.advance(); Assert.fail("an exception should have been thrown"); } catch (ConcurrentModificationException cme) { // expected } } /** * Regression test for a bug in findInsertionIndex where the hashing in the second probing * loop was inconsistent with the first causing duplicate keys after the right sequence * of puts and removes. */ @Test public void testPutKeysWithCollisions() { OpenIntToDoubleHashMap map = new OpenIntToDoubleHashMap(); int key1 = -1996012590; double value1 = 1.0; map.put(key1, value1); int key2 = 835099822; map.put(key2, value1); int key3 = 1008859686; map.put(key3, value1); Assert.assertTrue(Precision.equals(value1, map.get(key3), 1)); Assert.assertEquals(3, map.size()); map.remove(key2); double value2 = 2.0; map.put(key3, value2); Assert.assertTrue(Precision.equals(value2, map.get(key3), 1)); Assert.assertEquals(2, map.size()); } /** * Similar to testPutKeysWithCollisions() but exercises the codepaths in a slightly * different manner. */ @Test public void testPutKeysWithCollision2() { OpenIntToDoubleHashMap map = new OpenIntToDoubleHashMap(); int key1 = 837989881; double value1 = 1.0; map.put(key1, value1); int key2 = 476463321; map.put(key2, value1); Assert.assertEquals(2, map.size()); Assert.assertTrue(Precision.equals(value1, map.get(key2), 1)); map.remove(key1); double value2 = 2.0; map.put(key2, value2); Assert.assertEquals(1, map.size()); Assert.assertTrue(Precision.equals(value2, map.get(key2), 1)); } }
[ { "be_test_class_file": "org/apache/commons/math3/util/OpenIntToDoubleHashMap.java", "be_test_class_name": "org.apache.commons.math3.util.OpenIntToDoubleHashMap", "be_test_function_name": "changeIndexSign", "be_test_function_signature": "(I)I", "line_numbers": [ "332" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/util/OpenIntToDoubleHashMap.java", "be_test_class_name": "org.apache.commons.math3.util.OpenIntToDoubleHashMap", "be_test_function_name": "computeCapacity", "be_test_function_signature": "(I)I", "line_numbers": [ "150", "151", "153", "154", "155", "156", "158" ], "method_line_rate": 0.7142857142857143 }, { "be_test_class_file": "org/apache/commons/math3/util/OpenIntToDoubleHashMap.java", "be_test_class_name": "org.apache.commons.math3.util.OpenIntToDoubleHashMap", "be_test_function_name": "containsKey", "be_test_function_signature": "(II)Z", "line_numbers": [ "382" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/util/OpenIntToDoubleHashMap.java", "be_test_class_name": "org.apache.commons.math3.util.OpenIntToDoubleHashMap", "be_test_function_name": "doRemove", "be_test_function_signature": "(I)D", "line_numbers": [ "391", "392", "393", "394", "395", "396", "397" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/util/OpenIntToDoubleHashMap.java", "be_test_class_name": "org.apache.commons.math3.util.OpenIntToDoubleHashMap", "be_test_function_name": "findInsertionIndex", "be_test_function_signature": "(I)I", "line_numbers": [ "256" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/util/OpenIntToDoubleHashMap.java", "be_test_class_name": "org.apache.commons.math3.util.OpenIntToDoubleHashMap", "be_test_function_name": "findInsertionIndex", "be_test_function_signature": "([I[BII)I", "line_numbers": [ "269", "270", "271", "272", "273", "274", "277", "278", "279", "281", "282", "283", "285", "286", "291", "292", "293", "296", "299", "301", "302", "304", "305", "306", "307", "310" ], "method_line_rate": 0.8076923076923077 }, { "be_test_class_file": "org/apache/commons/math3/util/OpenIntToDoubleHashMap.java", "be_test_class_name": "org.apache.commons.math3.util.OpenIntToDoubleHashMap", "be_test_function_name": "get", "be_test_function_signature": "(I)D", "line_numbers": [ "177", "178", "179", "180", "183", "184", "187", "188", "189", "190", "191", "192", "196" ], "method_line_rate": 0.7692307692307693 }, { "be_test_class_file": "org/apache/commons/math3/util/OpenIntToDoubleHashMap.java", "be_test_class_name": "org.apache.commons.math3.util.OpenIntToDoubleHashMap", "be_test_function_name": "hashOf", "be_test_function_signature": "(I)I", "line_numbers": [ "475", "476" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/util/OpenIntToDoubleHashMap.java", "be_test_class_name": "org.apache.commons.math3.util.OpenIntToDoubleHashMap", "be_test_function_name": "perturb", "be_test_function_signature": "(I)I", "line_numbers": [ "247" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/util/OpenIntToDoubleHashMap.java", "be_test_class_name": "org.apache.commons.math3.util.OpenIntToDoubleHashMap", "be_test_function_name": "probe", "be_test_function_signature": "(II)I", "line_numbers": [ "323" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/util/OpenIntToDoubleHashMap.java", "be_test_class_name": "org.apache.commons.math3.util.OpenIntToDoubleHashMap", "be_test_function_name": "put", "be_test_function_signature": "(ID)D", "line_numbers": [ "407", "408", "409", "410", "411", "412", "413", "415", "416", "417", "418", "419", "420", "421", "423", "425" ], "method_line_rate": 0.9375 }, { "be_test_class_file": "org/apache/commons/math3/util/OpenIntToDoubleHashMap.java", "be_test_class_name": "org.apache.commons.math3.util.OpenIntToDoubleHashMap", "be_test_function_name": "remove", "be_test_function_signature": "(I)D", "line_numbers": [ "351", "352", "353", "354", "357", "358", "361", "362", "363", "364", "365", "366", "370" ], "method_line_rate": 0.3076923076923077 }, { "be_test_class_file": "org/apache/commons/math3/util/OpenIntToDoubleHashMap.java", "be_test_class_name": "org.apache.commons.math3.util.OpenIntToDoubleHashMap", "be_test_function_name": "shouldGrowTable", "be_test_function_signature": "()Z", "line_numbers": [ "466" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/util/OpenIntToDoubleHashMap.java", "be_test_class_name": "org.apache.commons.math3.util.OpenIntToDoubleHashMap", "be_test_function_name": "size", "be_test_function_signature": "()I", "line_numbers": [ "340" ], "method_line_rate": 1 } ]
public class DefaultTableXYDatasetTests extends TestCase
public void testAddSeries() { DefaultTableXYDataset d1 = new DefaultTableXYDataset(); d1.setAutoWidth(true); XYSeries s1 = new XYSeries("Series 1", true, false); s1.add(3.0, 1.1); s1.add(7.0, 2.2); d1.addSeries(s1); assertEquals(3.0, d1.getXValue(0, 0), EPSILON); assertEquals(7.0, d1.getXValue(0, 1), EPSILON); assertEquals(1.0, d1.getStartXValue(0, 0), EPSILON); assertEquals(5.0, d1.getStartXValue(0, 1), EPSILON); assertEquals(5.0, d1.getEndXValue(0, 0), EPSILON); assertEquals(9.0, d1.getEndXValue(0, 1), EPSILON); // now add another series XYSeries s2 = new XYSeries("Series 2", true, false); s2.add(7.5, 1.1); s2.add(9.0, 2.2); d1.addSeries(s2); assertEquals(3.0, d1.getXValue(1, 0), EPSILON); assertEquals(7.0, d1.getXValue(1, 1), EPSILON); assertEquals(7.5, d1.getXValue(1, 2), EPSILON); assertEquals(9.0, d1.getXValue(1, 3), EPSILON); assertEquals(7.25, d1.getStartXValue(1, 2), EPSILON); assertEquals(8.75, d1.getStartXValue(1, 3), EPSILON); assertEquals(7.75, d1.getEndXValue(1, 2), EPSILON); assertEquals(9.25, d1.getEndXValue(1, 3), EPSILON); // and check the first series too... assertEquals(2.75, d1.getStartXValue(0, 0), EPSILON); assertEquals(6.75, d1.getStartXValue(0, 1), EPSILON); assertEquals(3.25, d1.getEndXValue(0, 0), EPSILON); assertEquals(7.25, d1.getEndXValue(0, 1), EPSILON); }
// // Abstract Java Tested Class // package org.jfree.data.xy; // // import java.util.ArrayList; // import java.util.HashSet; // import java.util.Iterator; // import java.util.List; // import org.jfree.chart.event.DatasetChangeInfo; // import org.jfree.chart.util.ObjectUtilities; // import org.jfree.chart.util.PublicCloneable; // import org.jfree.data.DomainInfo; // import org.jfree.data.Range; // import org.jfree.data.event.DatasetChangeEvent; // import org.jfree.data.general.DatasetUtilities; // import org.jfree.data.event.SeriesChangeEvent; // // // // public class DefaultTableXYDataset extends AbstractIntervalXYDataset // implements TableXYDataset, IntervalXYDataset, DomainInfo, // PublicCloneable { // private List data = null; // private HashSet xPoints = null; // private boolean propagateEvents = true; // private boolean autoPrune = false; // private IntervalXYDelegate intervalDelegate; // // public DefaultTableXYDataset(); // public DefaultTableXYDataset(boolean autoPrune); // public boolean isAutoPrune(); // public void addSeries(XYSeries series); // private void updateXPoints(XYSeries series); // public void updateXPoints(); // public int getSeriesCount(); // public int getItemCount(); // public XYSeries getSeries(int series); // public Comparable getSeriesKey(int series); // public int getItemCount(int series); // public Number getX(int series, int item); // public Number getStartX(int series, int item); // public Number getEndX(int series, int item); // public Number getY(int series, int index); // public Number getStartY(int series, int item); // public Number getEndY(int series, int item); // public void removeAllSeries(); // public void removeSeries(XYSeries series); // public void removeSeries(int series); // public void removeAllValuesForX(Number x); // protected boolean canPrune(Number x); // public void prune(); // public void seriesChanged(SeriesChangeEvent event); // public boolean equals(Object obj); // public int hashCode(); // public Object clone() throws CloneNotSupportedException; // public double getDomainLowerBound(boolean includeInterval); // public double getDomainUpperBound(boolean includeInterval); // public Range getDomainBounds(boolean includeInterval); // public double getIntervalPositionFactor(); // public void setIntervalPositionFactor(double d); // public double getIntervalWidth(); // public void setIntervalWidth(double d); // public boolean isAutoWidth(); // public void setAutoWidth(boolean b); // } // // // Abstract Java Test Class // package org.jfree.data.xy.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.chart.util.PublicCloneable; // import org.jfree.data.xy.DefaultTableXYDataset; // import org.jfree.data.xy.XYSeries; // // // // public class DefaultTableXYDatasetTests extends TestCase { // private static final double EPSILON = 0.0000000001; // // public static Test suite(); // public DefaultTableXYDatasetTests(String name); // public void testEquals(); // public void testCloning(); // public void testPublicCloneable(); // public void testSerialization(); // public void testAddSeries(); // public void testGetSeries(); // } // You are a professional Java test case writer, please create a test case named `testAddSeries` for the `DefaultTableXYDataset` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * This is a test for bug 1312066 - adding a new series should trigger a * recalculation of the interval width, if it is being automatically * calculated. */
tests/org/jfree/data/xy/junit/DefaultTableXYDatasetTests.java
package org.jfree.data.xy; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import org.jfree.chart.event.DatasetChangeInfo; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.DomainInfo; import org.jfree.data.Range; import org.jfree.data.event.DatasetChangeEvent; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.event.SeriesChangeEvent;
public DefaultTableXYDataset(); public DefaultTableXYDataset(boolean autoPrune); public boolean isAutoPrune(); public void addSeries(XYSeries series); private void updateXPoints(XYSeries series); public void updateXPoints(); public int getSeriesCount(); public int getItemCount(); public XYSeries getSeries(int series); public Comparable getSeriesKey(int series); public int getItemCount(int series); public Number getX(int series, int item); public Number getStartX(int series, int item); public Number getEndX(int series, int item); public Number getY(int series, int index); public Number getStartY(int series, int item); public Number getEndY(int series, int item); public void removeAllSeries(); public void removeSeries(XYSeries series); public void removeSeries(int series); public void removeAllValuesForX(Number x); protected boolean canPrune(Number x); public void prune(); public void seriesChanged(SeriesChangeEvent event); public boolean equals(Object obj); public int hashCode(); public Object clone() throws CloneNotSupportedException; public double getDomainLowerBound(boolean includeInterval); public double getDomainUpperBound(boolean includeInterval); public Range getDomainBounds(boolean includeInterval); public double getIntervalPositionFactor(); public void setIntervalPositionFactor(double d); public double getIntervalWidth(); public void setIntervalWidth(double d); public boolean isAutoWidth(); public void setAutoWidth(boolean b);
217
testAddSeries
```java // Abstract Java Tested Class package org.jfree.data.xy; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import org.jfree.chart.event.DatasetChangeInfo; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.DomainInfo; import org.jfree.data.Range; import org.jfree.data.event.DatasetChangeEvent; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.event.SeriesChangeEvent; public class DefaultTableXYDataset extends AbstractIntervalXYDataset implements TableXYDataset, IntervalXYDataset, DomainInfo, PublicCloneable { private List data = null; private HashSet xPoints = null; private boolean propagateEvents = true; private boolean autoPrune = false; private IntervalXYDelegate intervalDelegate; public DefaultTableXYDataset(); public DefaultTableXYDataset(boolean autoPrune); public boolean isAutoPrune(); public void addSeries(XYSeries series); private void updateXPoints(XYSeries series); public void updateXPoints(); public int getSeriesCount(); public int getItemCount(); public XYSeries getSeries(int series); public Comparable getSeriesKey(int series); public int getItemCount(int series); public Number getX(int series, int item); public Number getStartX(int series, int item); public Number getEndX(int series, int item); public Number getY(int series, int index); public Number getStartY(int series, int item); public Number getEndY(int series, int item); public void removeAllSeries(); public void removeSeries(XYSeries series); public void removeSeries(int series); public void removeAllValuesForX(Number x); protected boolean canPrune(Number x); public void prune(); public void seriesChanged(SeriesChangeEvent event); public boolean equals(Object obj); public int hashCode(); public Object clone() throws CloneNotSupportedException; public double getDomainLowerBound(boolean includeInterval); public double getDomainUpperBound(boolean includeInterval); public Range getDomainBounds(boolean includeInterval); public double getIntervalPositionFactor(); public void setIntervalPositionFactor(double d); public double getIntervalWidth(); public void setIntervalWidth(double d); public boolean isAutoWidth(); public void setAutoWidth(boolean b); } // Abstract Java Test Class package org.jfree.data.xy.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.chart.util.PublicCloneable; import org.jfree.data.xy.DefaultTableXYDataset; import org.jfree.data.xy.XYSeries; public class DefaultTableXYDatasetTests extends TestCase { private static final double EPSILON = 0.0000000001; public static Test suite(); public DefaultTableXYDatasetTests(String name); public void testEquals(); public void testCloning(); public void testPublicCloneable(); public void testSerialization(); public void testAddSeries(); public void testGetSeries(); } ``` You are a professional Java test case writer, please create a test case named `testAddSeries` for the `DefaultTableXYDataset` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * This is a test for bug 1312066 - adding a new series should trigger a * recalculation of the interval width, if it is being automatically * calculated. */
182
// // Abstract Java Tested Class // package org.jfree.data.xy; // // import java.util.ArrayList; // import java.util.HashSet; // import java.util.Iterator; // import java.util.List; // import org.jfree.chart.event.DatasetChangeInfo; // import org.jfree.chart.util.ObjectUtilities; // import org.jfree.chart.util.PublicCloneable; // import org.jfree.data.DomainInfo; // import org.jfree.data.Range; // import org.jfree.data.event.DatasetChangeEvent; // import org.jfree.data.general.DatasetUtilities; // import org.jfree.data.event.SeriesChangeEvent; // // // // public class DefaultTableXYDataset extends AbstractIntervalXYDataset // implements TableXYDataset, IntervalXYDataset, DomainInfo, // PublicCloneable { // private List data = null; // private HashSet xPoints = null; // private boolean propagateEvents = true; // private boolean autoPrune = false; // private IntervalXYDelegate intervalDelegate; // // public DefaultTableXYDataset(); // public DefaultTableXYDataset(boolean autoPrune); // public boolean isAutoPrune(); // public void addSeries(XYSeries series); // private void updateXPoints(XYSeries series); // public void updateXPoints(); // public int getSeriesCount(); // public int getItemCount(); // public XYSeries getSeries(int series); // public Comparable getSeriesKey(int series); // public int getItemCount(int series); // public Number getX(int series, int item); // public Number getStartX(int series, int item); // public Number getEndX(int series, int item); // public Number getY(int series, int index); // public Number getStartY(int series, int item); // public Number getEndY(int series, int item); // public void removeAllSeries(); // public void removeSeries(XYSeries series); // public void removeSeries(int series); // public void removeAllValuesForX(Number x); // protected boolean canPrune(Number x); // public void prune(); // public void seriesChanged(SeriesChangeEvent event); // public boolean equals(Object obj); // public int hashCode(); // public Object clone() throws CloneNotSupportedException; // public double getDomainLowerBound(boolean includeInterval); // public double getDomainUpperBound(boolean includeInterval); // public Range getDomainBounds(boolean includeInterval); // public double getIntervalPositionFactor(); // public void setIntervalPositionFactor(double d); // public double getIntervalWidth(); // public void setIntervalWidth(double d); // public boolean isAutoWidth(); // public void setAutoWidth(boolean b); // } // // // Abstract Java Test Class // package org.jfree.data.xy.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.chart.util.PublicCloneable; // import org.jfree.data.xy.DefaultTableXYDataset; // import org.jfree.data.xy.XYSeries; // // // // public class DefaultTableXYDatasetTests extends TestCase { // private static final double EPSILON = 0.0000000001; // // public static Test suite(); // public DefaultTableXYDatasetTests(String name); // public void testEquals(); // public void testCloning(); // public void testPublicCloneable(); // public void testSerialization(); // public void testAddSeries(); // public void testGetSeries(); // } // You are a professional Java test case writer, please create a test case named `testAddSeries` for the `DefaultTableXYDataset` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * This is a test for bug 1312066 - adding a new series should trigger a * recalculation of the interval width, if it is being automatically * calculated. */ public void testAddSeries() {
/** * This is a test for bug 1312066 - adding a new series should trigger a * recalculation of the interval width, if it is being automatically * calculated. */
1
org.jfree.data.xy.DefaultTableXYDataset
tests
```java // Abstract Java Tested Class package org.jfree.data.xy; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import org.jfree.chart.event.DatasetChangeInfo; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.DomainInfo; import org.jfree.data.Range; import org.jfree.data.event.DatasetChangeEvent; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.event.SeriesChangeEvent; public class DefaultTableXYDataset extends AbstractIntervalXYDataset implements TableXYDataset, IntervalXYDataset, DomainInfo, PublicCloneable { private List data = null; private HashSet xPoints = null; private boolean propagateEvents = true; private boolean autoPrune = false; private IntervalXYDelegate intervalDelegate; public DefaultTableXYDataset(); public DefaultTableXYDataset(boolean autoPrune); public boolean isAutoPrune(); public void addSeries(XYSeries series); private void updateXPoints(XYSeries series); public void updateXPoints(); public int getSeriesCount(); public int getItemCount(); public XYSeries getSeries(int series); public Comparable getSeriesKey(int series); public int getItemCount(int series); public Number getX(int series, int item); public Number getStartX(int series, int item); public Number getEndX(int series, int item); public Number getY(int series, int index); public Number getStartY(int series, int item); public Number getEndY(int series, int item); public void removeAllSeries(); public void removeSeries(XYSeries series); public void removeSeries(int series); public void removeAllValuesForX(Number x); protected boolean canPrune(Number x); public void prune(); public void seriesChanged(SeriesChangeEvent event); public boolean equals(Object obj); public int hashCode(); public Object clone() throws CloneNotSupportedException; public double getDomainLowerBound(boolean includeInterval); public double getDomainUpperBound(boolean includeInterval); public Range getDomainBounds(boolean includeInterval); public double getIntervalPositionFactor(); public void setIntervalPositionFactor(double d); public double getIntervalWidth(); public void setIntervalWidth(double d); public boolean isAutoWidth(); public void setAutoWidth(boolean b); } // Abstract Java Test Class package org.jfree.data.xy.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.chart.util.PublicCloneable; import org.jfree.data.xy.DefaultTableXYDataset; import org.jfree.data.xy.XYSeries; public class DefaultTableXYDatasetTests extends TestCase { private static final double EPSILON = 0.0000000001; public static Test suite(); public DefaultTableXYDatasetTests(String name); public void testEquals(); public void testCloning(); public void testPublicCloneable(); public void testSerialization(); public void testAddSeries(); public void testGetSeries(); } ``` You are a professional Java test case writer, please create a test case named `testAddSeries` for the `DefaultTableXYDataset` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * This is a test for bug 1312066 - adding a new series should trigger a * recalculation of the interval width, if it is being automatically * calculated. */ public void testAddSeries() { ```
public class DefaultTableXYDataset extends AbstractIntervalXYDataset implements TableXYDataset, IntervalXYDataset, DomainInfo, PublicCloneable
package org.jfree.data.xy.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.chart.util.PublicCloneable; import org.jfree.data.xy.DefaultTableXYDataset; import org.jfree.data.xy.XYSeries;
public static Test suite(); public DefaultTableXYDatasetTests(String name); public void testEquals(); public void testCloning(); public void testPublicCloneable(); public void testSerialization(); public void testAddSeries(); public void testGetSeries();
265a5d4ec881ad36b6e99b2f701f71a00dca442ce6bcc1b19915ea81e9343cf7
[ "org.jfree.data.xy.junit.DefaultTableXYDatasetTests::testAddSeries" ]
private List data = null; private HashSet xPoints = null; private boolean propagateEvents = true; private boolean autoPrune = false; private IntervalXYDelegate intervalDelegate;
public void testAddSeries()
private static final double EPSILON = 0.0000000001;
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.] * * ------------------------------- * DefaultTableXYDatasetTests.java * ------------------------------- * (C) Copyright 2003-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 23-Dec-2003 : Version 1 (DG); * 06-Oct-2005 : Added test for new data updating interval width (DG); * 08-Mar-2007 : Added testGetSeries() (DG); * 22-Apr-2008 : Added testPublicCloneable (DG); * */ package org.jfree.data.xy.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.chart.util.PublicCloneable; import org.jfree.data.xy.DefaultTableXYDataset; import org.jfree.data.xy.XYSeries; /** * Tests for the {@link DefaultTableXYDataset} class. */ public class DefaultTableXYDatasetTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(DefaultTableXYDatasetTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public DefaultTableXYDatasetTests(String name) { super(name); } /** * Confirm that the equals method can distinguish all the required fields. */ public void testEquals() { DefaultTableXYDataset d1 = new DefaultTableXYDataset(); XYSeries s1 = new XYSeries("Series 1", true, false); s1.add(1.0, 1.1); s1.add(2.0, 2.2); d1.addSeries(s1); DefaultTableXYDataset d2 = new DefaultTableXYDataset(); XYSeries s2 = new XYSeries("Series 1", true, false); s2.add(1.0, 1.1); s2.add(2.0, 2.2); d2.addSeries(s2); assertTrue(d1.equals(d2)); assertTrue(d2.equals(d1)); s1.add(3.0, 3.3); assertFalse(d1.equals(d2)); s2.add(3.0, 3.3); assertTrue(d1.equals(d2)); } /** * Confirm that cloning works. */ public void testCloning() { DefaultTableXYDataset d1 = new DefaultTableXYDataset(); XYSeries s1 = new XYSeries("Series 1", true, false); s1.add(1.0, 1.1); s1.add(2.0, 2.2); d1.addSeries(s1); DefaultTableXYDataset d2 = null; try { d2 = (DefaultTableXYDataset) d1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(d1 != d2); assertTrue(d1.getClass() == d2.getClass()); assertTrue(d1.equals(d2)); s1.add(3.0, 3.3); assertFalse(d1.equals(d2)); } /** * Verify that this class implements {@link PublicCloneable}. */ public void testPublicCloneable() { DefaultTableXYDataset d1 = new DefaultTableXYDataset(); assertTrue(d1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { DefaultTableXYDataset d1 = new DefaultTableXYDataset(); XYSeries s1 = new XYSeries("Series 1", true, false); s1.add(1.0, 1.1); s1.add(2.0, 2.2); d1.addSeries(s1); DefaultTableXYDataset d2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(d1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); d2 = (DefaultTableXYDataset) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(d1, d2); } private static final double EPSILON = 0.0000000001; /** * This is a test for bug 1312066 - adding a new series should trigger a * recalculation of the interval width, if it is being automatically * calculated. */ public void testAddSeries() { DefaultTableXYDataset d1 = new DefaultTableXYDataset(); d1.setAutoWidth(true); XYSeries s1 = new XYSeries("Series 1", true, false); s1.add(3.0, 1.1); s1.add(7.0, 2.2); d1.addSeries(s1); assertEquals(3.0, d1.getXValue(0, 0), EPSILON); assertEquals(7.0, d1.getXValue(0, 1), EPSILON); assertEquals(1.0, d1.getStartXValue(0, 0), EPSILON); assertEquals(5.0, d1.getStartXValue(0, 1), EPSILON); assertEquals(5.0, d1.getEndXValue(0, 0), EPSILON); assertEquals(9.0, d1.getEndXValue(0, 1), EPSILON); // now add another series XYSeries s2 = new XYSeries("Series 2", true, false); s2.add(7.5, 1.1); s2.add(9.0, 2.2); d1.addSeries(s2); assertEquals(3.0, d1.getXValue(1, 0), EPSILON); assertEquals(7.0, d1.getXValue(1, 1), EPSILON); assertEquals(7.5, d1.getXValue(1, 2), EPSILON); assertEquals(9.0, d1.getXValue(1, 3), EPSILON); assertEquals(7.25, d1.getStartXValue(1, 2), EPSILON); assertEquals(8.75, d1.getStartXValue(1, 3), EPSILON); assertEquals(7.75, d1.getEndXValue(1, 2), EPSILON); assertEquals(9.25, d1.getEndXValue(1, 3), EPSILON); // and check the first series too... assertEquals(2.75, d1.getStartXValue(0, 0), EPSILON); assertEquals(6.75, d1.getStartXValue(0, 1), EPSILON); assertEquals(3.25, d1.getEndXValue(0, 0), EPSILON); assertEquals(7.25, d1.getEndXValue(0, 1), EPSILON); } /** * Some basic checks for the getSeries() method. */ public void testGetSeries() { DefaultTableXYDataset d1 = new DefaultTableXYDataset(); XYSeries s1 = new XYSeries("Series 1", true, false); d1.addSeries(s1); assertEquals("Series 1", d1.getSeries(0).getKey()); boolean pass = false; try { d1.getSeries(-1); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); pass = false; try { d1.getSeries(1); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); } }
[ { "be_test_class_file": "org/jfree/data/xy/DefaultTableXYDataset.java", "be_test_class_name": "org.jfree.data.xy.DefaultTableXYDataset", "be_test_function_name": "addSeries", "be_test_function_signature": "(Lorg/jfree/data/xy/XYSeries;)V", "line_numbers": [ "146", "147", "149", "150", "155", "156", "157", "158", "160" ], "method_line_rate": 0.7777777777777778 }, { "be_test_class_file": "org/jfree/data/xy/DefaultTableXYDataset.java", "be_test_class_name": "org.jfree.data.xy.DefaultTableXYDataset", "be_test_function_name": "getEndX", "be_test_function_signature": "(II)Ljava/lang/Number;", "line_numbers": [ "308" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/xy/DefaultTableXYDataset.java", "be_test_class_name": "org.jfree.data.xy.DefaultTableXYDataset", "be_test_function_name": "getItemCount", "be_test_function_signature": "(I)I", "line_numbers": [ "271" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/xy/DefaultTableXYDataset.java", "be_test_class_name": "org.jfree.data.xy.DefaultTableXYDataset", "be_test_function_name": "getSeries", "be_test_function_signature": "(I)Lorg/jfree/data/xy/XYSeries;", "line_numbers": [ "244", "245", "247" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "org/jfree/data/xy/DefaultTableXYDataset.java", "be_test_class_name": "org.jfree.data.xy.DefaultTableXYDataset", "be_test_function_name": "getSeriesCount", "be_test_function_signature": "()I", "line_numbers": [ "219" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/xy/DefaultTableXYDataset.java", "be_test_class_name": "org.jfree.data.xy.DefaultTableXYDataset", "be_test_function_name": "getStartX", "be_test_function_signature": "(II)Ljava/lang/Number;", "line_numbers": [ "296" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/xy/DefaultTableXYDataset.java", "be_test_class_name": "org.jfree.data.xy.DefaultTableXYDataset", "be_test_function_name": "getX", "be_test_function_signature": "(II)Ljava/lang/Number;", "line_numbers": [ "283", "284" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/xy/DefaultTableXYDataset.java", "be_test_class_name": "org.jfree.data.xy.DefaultTableXYDataset", "be_test_function_name": "seriesChanged", "be_test_function_signature": "(Lorg/jfree/data/event/SeriesChangeEvent;)V", "line_numbers": [ "484", "485", "486", "489" ], "method_line_rate": 0.5 }, { "be_test_class_file": "org/jfree/data/xy/DefaultTableXYDataset.java", "be_test_class_name": "org.jfree.data.xy.DefaultTableXYDataset", "be_test_function_name": "setAutoWidth", "be_test_function_signature": "(Z)V", "line_numbers": [ "665", "666", "668" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/xy/DefaultTableXYDataset.java", "be_test_class_name": "org.jfree.data.xy.DefaultTableXYDataset", "be_test_function_name": "updateXPoints", "be_test_function_signature": "(Lorg/jfree/data/xy/XYSeries;)V", "line_numbers": [ "169", "170", "172", "173", "174", "175", "176", "177", "178", "179", "180", "181", "182", "183", "184", "189", "190", "191", "192", "193", "195", "196", "197" ], "method_line_rate": 0.9565217391304348 } ]
public class MultiBackgroundInitializerTest
@Test(expected = NoSuchElementException.class) public void testResultIsExceptionUnknown() throws ConcurrentException { final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize(); res.isException("unknown"); }
// // 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 `testResultIsExceptionUnknown` for the `MultiBackgroundInitializer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tries to query the exception flag of an unknown child initializer from * the results object. This should cause an exception. */
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);
236
testResultIsExceptionUnknown
```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 `testResultIsExceptionUnknown` for the `MultiBackgroundInitializer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tries to query the exception flag of an unknown child initializer from * the results object. This should cause an exception. */
232
// // 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 `testResultIsExceptionUnknown` for the `MultiBackgroundInitializer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * 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 {
/** * Tries to query the exception flag of an unknown child initializer from * the results object. This should cause an exception. */
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 `testResultIsExceptionUnknown` for the `MultiBackgroundInitializer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * 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 { ```
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;
27e129a9ab16dddff74de0cd8e2675bd9f7dd7ad97180d2f9cd3ee99adeec189
[ "org.apache.commons.lang3.concurrent.MultiBackgroundInitializerTest::testResultIsExceptionUnknown" ]
private final Map<String, BackgroundInitializer<?>> childInitializers = new HashMap<String, BackgroundInitializer<?>>();
@Test(expected = NoSuchElementException.class) public void testResultIsExceptionUnknown() 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 final class PolynomialFunctionTest
@Test public void testfirstDerivativeComparison() { double[] f_coeff = { 3, 6, -2, 1 }; double[] g_coeff = { 6, -4, 3 }; double[] h_coeff = { -4, 6 }; PolynomialFunction f = new PolynomialFunction(f_coeff); PolynomialFunction g = new PolynomialFunction(g_coeff); PolynomialFunction h = new PolynomialFunction(h_coeff); // compare f' = g Assert.assertEquals(f.derivative().value(0), g.value(0), tolerance); Assert.assertEquals(f.derivative().value(1), g.value(1), tolerance); Assert.assertEquals(f.derivative().value(100), g.value(100), tolerance); Assert.assertEquals(f.derivative().value(4.1), g.value(4.1), tolerance); Assert.assertEquals(f.derivative().value(-3.25), g.value(-3.25), tolerance); // compare g' = h Assert.assertEquals(g.derivative().value(FastMath.PI), h.value(FastMath.PI), tolerance); Assert.assertEquals(g.derivative().value(FastMath.E), h.value(FastMath.E), tolerance); }
// // Abstract Java Tested Class // package org.apache.commons.math3.analysis.polynomials; // // import java.io.Serializable; // import java.util.Arrays; // import org.apache.commons.math3.exception.util.LocalizedFormats; // import org.apache.commons.math3.exception.NoDataException; // import org.apache.commons.math3.exception.NullArgumentException; // import org.apache.commons.math3.analysis.DifferentiableUnivariateFunction; // import org.apache.commons.math3.analysis.UnivariateFunction; // import org.apache.commons.math3.analysis.ParametricUnivariateFunction; // import org.apache.commons.math3.analysis.differentiation.DerivativeStructure; // import org.apache.commons.math3.analysis.differentiation.UnivariateDifferentiableFunction; // import org.apache.commons.math3.util.FastMath; // import org.apache.commons.math3.util.MathUtils; // // // // public class PolynomialFunction implements UnivariateDifferentiableFunction, DifferentiableUnivariateFunction, Serializable { // private static final long serialVersionUID = -7726511984200295583L; // private final double coefficients[]; // // public PolynomialFunction(double c[]) // throws NullArgumentException, NoDataException; // public double value(double x); // public int degree(); // public double[] getCoefficients(); // protected static double evaluate(double[] coefficients, double argument) // throws NullArgumentException, NoDataException; // public DerivativeStructure value(final DerivativeStructure t) // throws NullArgumentException, NoDataException; // public PolynomialFunction add(final PolynomialFunction p); // public PolynomialFunction subtract(final PolynomialFunction p); // public PolynomialFunction negate(); // public PolynomialFunction multiply(final PolynomialFunction p); // protected static double[] differentiate(double[] coefficients) // throws NullArgumentException, NoDataException; // public PolynomialFunction polynomialDerivative(); // public UnivariateFunction derivative(); // @Override // public String toString(); // private static String toString(double coeff); // @Override // public int hashCode(); // @Override // public boolean equals(Object obj); // public double[] gradient(double x, double ... parameters); // public double value(final double x, final double ... parameters) // throws NoDataException; // } // // // Abstract Java Test Class // package org.apache.commons.math3.analysis.polynomials; // // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.util.FastMath; // import org.junit.Test; // import org.junit.Assert; // // // // public final class PolynomialFunctionTest { // protected double tolerance = 1e-12; // // @Test // public void testConstants(); // @Test // public void testLinear(); // @Test // public void testQuadratic(); // @Test // public void testQuintic(); // @Test // public void testfirstDerivativeComparison(); // @Test // public void testString(); // @Test // public void testAddition(); // @Test // public void testSubtraction(); // @Test // public void testMultiplication(); // @Test // public void testSerial(); // @Test // public void testMath341(); // public void checkPolynomial(PolynomialFunction p, String reference); // private void checkNullPolynomial(PolynomialFunction p); // } // You are a professional Java test case writer, please create a test case named `testfirstDerivativeComparison` for the `PolynomialFunction` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * tests the firstDerivative function by comparison * * <p>This will test the functions * <tt>f(x) = x^3 - 2x^2 + 6x + 3, g(x) = 3x^2 - 4x + 6</tt> * and <tt>h(x) = 6x - 4</tt> */
src/test/java/org/apache/commons/math3/analysis/polynomials/PolynomialFunctionTest.java
package org.apache.commons.math3.analysis.polynomials; import java.io.Serializable; import java.util.Arrays; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.exception.NoDataException; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.analysis.DifferentiableUnivariateFunction; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.ParametricUnivariateFunction; import org.apache.commons.math3.analysis.differentiation.DerivativeStructure; import org.apache.commons.math3.analysis.differentiation.UnivariateDifferentiableFunction; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.MathUtils;
public PolynomialFunction(double c[]) throws NullArgumentException, NoDataException; public double value(double x); public int degree(); public double[] getCoefficients(); protected static double evaluate(double[] coefficients, double argument) throws NullArgumentException, NoDataException; public DerivativeStructure value(final DerivativeStructure t) throws NullArgumentException, NoDataException; public PolynomialFunction add(final PolynomialFunction p); public PolynomialFunction subtract(final PolynomialFunction p); public PolynomialFunction negate(); public PolynomialFunction multiply(final PolynomialFunction p); protected static double[] differentiate(double[] coefficients) throws NullArgumentException, NoDataException; public PolynomialFunction polynomialDerivative(); public UnivariateFunction derivative(); @Override public String toString(); private static String toString(double coeff); @Override public int hashCode(); @Override public boolean equals(Object obj); public double[] gradient(double x, double ... parameters); public double value(final double x, final double ... parameters) throws NoDataException;
154
testfirstDerivativeComparison
```java // Abstract Java Tested Class package org.apache.commons.math3.analysis.polynomials; import java.io.Serializable; import java.util.Arrays; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.exception.NoDataException; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.analysis.DifferentiableUnivariateFunction; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.ParametricUnivariateFunction; import org.apache.commons.math3.analysis.differentiation.DerivativeStructure; import org.apache.commons.math3.analysis.differentiation.UnivariateDifferentiableFunction; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.MathUtils; public class PolynomialFunction implements UnivariateDifferentiableFunction, DifferentiableUnivariateFunction, Serializable { private static final long serialVersionUID = -7726511984200295583L; private final double coefficients[]; public PolynomialFunction(double c[]) throws NullArgumentException, NoDataException; public double value(double x); public int degree(); public double[] getCoefficients(); protected static double evaluate(double[] coefficients, double argument) throws NullArgumentException, NoDataException; public DerivativeStructure value(final DerivativeStructure t) throws NullArgumentException, NoDataException; public PolynomialFunction add(final PolynomialFunction p); public PolynomialFunction subtract(final PolynomialFunction p); public PolynomialFunction negate(); public PolynomialFunction multiply(final PolynomialFunction p); protected static double[] differentiate(double[] coefficients) throws NullArgumentException, NoDataException; public PolynomialFunction polynomialDerivative(); public UnivariateFunction derivative(); @Override public String toString(); private static String toString(double coeff); @Override public int hashCode(); @Override public boolean equals(Object obj); public double[] gradient(double x, double ... parameters); public double value(final double x, final double ... parameters) throws NoDataException; } // Abstract Java Test Class package org.apache.commons.math3.analysis.polynomials; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert; public final class PolynomialFunctionTest { protected double tolerance = 1e-12; @Test public void testConstants(); @Test public void testLinear(); @Test public void testQuadratic(); @Test public void testQuintic(); @Test public void testfirstDerivativeComparison(); @Test public void testString(); @Test public void testAddition(); @Test public void testSubtraction(); @Test public void testMultiplication(); @Test public void testSerial(); @Test public void testMath341(); public void checkPolynomial(PolynomialFunction p, String reference); private void checkNullPolynomial(PolynomialFunction p); } ``` You are a professional Java test case writer, please create a test case named `testfirstDerivativeComparison` for the `PolynomialFunction` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * tests the firstDerivative function by comparison * * <p>This will test the functions * <tt>f(x) = x^3 - 2x^2 + 6x + 3, g(x) = 3x^2 - 4x + 6</tt> * and <tt>h(x) = 6x - 4</tt> */
134
// // Abstract Java Tested Class // package org.apache.commons.math3.analysis.polynomials; // // import java.io.Serializable; // import java.util.Arrays; // import org.apache.commons.math3.exception.util.LocalizedFormats; // import org.apache.commons.math3.exception.NoDataException; // import org.apache.commons.math3.exception.NullArgumentException; // import org.apache.commons.math3.analysis.DifferentiableUnivariateFunction; // import org.apache.commons.math3.analysis.UnivariateFunction; // import org.apache.commons.math3.analysis.ParametricUnivariateFunction; // import org.apache.commons.math3.analysis.differentiation.DerivativeStructure; // import org.apache.commons.math3.analysis.differentiation.UnivariateDifferentiableFunction; // import org.apache.commons.math3.util.FastMath; // import org.apache.commons.math3.util.MathUtils; // // // // public class PolynomialFunction implements UnivariateDifferentiableFunction, DifferentiableUnivariateFunction, Serializable { // private static final long serialVersionUID = -7726511984200295583L; // private final double coefficients[]; // // public PolynomialFunction(double c[]) // throws NullArgumentException, NoDataException; // public double value(double x); // public int degree(); // public double[] getCoefficients(); // protected static double evaluate(double[] coefficients, double argument) // throws NullArgumentException, NoDataException; // public DerivativeStructure value(final DerivativeStructure t) // throws NullArgumentException, NoDataException; // public PolynomialFunction add(final PolynomialFunction p); // public PolynomialFunction subtract(final PolynomialFunction p); // public PolynomialFunction negate(); // public PolynomialFunction multiply(final PolynomialFunction p); // protected static double[] differentiate(double[] coefficients) // throws NullArgumentException, NoDataException; // public PolynomialFunction polynomialDerivative(); // public UnivariateFunction derivative(); // @Override // public String toString(); // private static String toString(double coeff); // @Override // public int hashCode(); // @Override // public boolean equals(Object obj); // public double[] gradient(double x, double ... parameters); // public double value(final double x, final double ... parameters) // throws NoDataException; // } // // // Abstract Java Test Class // package org.apache.commons.math3.analysis.polynomials; // // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.util.FastMath; // import org.junit.Test; // import org.junit.Assert; // // // // public final class PolynomialFunctionTest { // protected double tolerance = 1e-12; // // @Test // public void testConstants(); // @Test // public void testLinear(); // @Test // public void testQuadratic(); // @Test // public void testQuintic(); // @Test // public void testfirstDerivativeComparison(); // @Test // public void testString(); // @Test // public void testAddition(); // @Test // public void testSubtraction(); // @Test // public void testMultiplication(); // @Test // public void testSerial(); // @Test // public void testMath341(); // public void checkPolynomial(PolynomialFunction p, String reference); // private void checkNullPolynomial(PolynomialFunction p); // } // You are a professional Java test case writer, please create a test case named `testfirstDerivativeComparison` for the `PolynomialFunction` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * tests the firstDerivative function by comparison * * <p>This will test the functions * <tt>f(x) = x^3 - 2x^2 + 6x + 3, g(x) = 3x^2 - 4x + 6</tt> * and <tt>h(x) = 6x - 4</tt> */ @Test public void testfirstDerivativeComparison() {
/** * tests the firstDerivative function by comparison * * <p>This will test the functions * <tt>f(x) = x^3 - 2x^2 + 6x + 3, g(x) = 3x^2 - 4x + 6</tt> * and <tt>h(x) = 6x - 4</tt> */
1
org.apache.commons.math3.analysis.polynomials.PolynomialFunction
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.math3.analysis.polynomials; import java.io.Serializable; import java.util.Arrays; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.exception.NoDataException; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.analysis.DifferentiableUnivariateFunction; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.ParametricUnivariateFunction; import org.apache.commons.math3.analysis.differentiation.DerivativeStructure; import org.apache.commons.math3.analysis.differentiation.UnivariateDifferentiableFunction; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.MathUtils; public class PolynomialFunction implements UnivariateDifferentiableFunction, DifferentiableUnivariateFunction, Serializable { private static final long serialVersionUID = -7726511984200295583L; private final double coefficients[]; public PolynomialFunction(double c[]) throws NullArgumentException, NoDataException; public double value(double x); public int degree(); public double[] getCoefficients(); protected static double evaluate(double[] coefficients, double argument) throws NullArgumentException, NoDataException; public DerivativeStructure value(final DerivativeStructure t) throws NullArgumentException, NoDataException; public PolynomialFunction add(final PolynomialFunction p); public PolynomialFunction subtract(final PolynomialFunction p); public PolynomialFunction negate(); public PolynomialFunction multiply(final PolynomialFunction p); protected static double[] differentiate(double[] coefficients) throws NullArgumentException, NoDataException; public PolynomialFunction polynomialDerivative(); public UnivariateFunction derivative(); @Override public String toString(); private static String toString(double coeff); @Override public int hashCode(); @Override public boolean equals(Object obj); public double[] gradient(double x, double ... parameters); public double value(final double x, final double ... parameters) throws NoDataException; } // Abstract Java Test Class package org.apache.commons.math3.analysis.polynomials; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert; public final class PolynomialFunctionTest { protected double tolerance = 1e-12; @Test public void testConstants(); @Test public void testLinear(); @Test public void testQuadratic(); @Test public void testQuintic(); @Test public void testfirstDerivativeComparison(); @Test public void testString(); @Test public void testAddition(); @Test public void testSubtraction(); @Test public void testMultiplication(); @Test public void testSerial(); @Test public void testMath341(); public void checkPolynomial(PolynomialFunction p, String reference); private void checkNullPolynomial(PolynomialFunction p); } ``` You are a professional Java test case writer, please create a test case named `testfirstDerivativeComparison` for the `PolynomialFunction` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * tests the firstDerivative function by comparison * * <p>This will test the functions * <tt>f(x) = x^3 - 2x^2 + 6x + 3, g(x) = 3x^2 - 4x + 6</tt> * and <tt>h(x) = 6x - 4</tt> */ @Test public void testfirstDerivativeComparison() { ```
public class PolynomialFunction implements UnivariateDifferentiableFunction, DifferentiableUnivariateFunction, Serializable
package org.apache.commons.math3.analysis.polynomials; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert;
@Test public void testConstants(); @Test public void testLinear(); @Test public void testQuadratic(); @Test public void testQuintic(); @Test public void testfirstDerivativeComparison(); @Test public void testString(); @Test public void testAddition(); @Test public void testSubtraction(); @Test public void testMultiplication(); @Test public void testSerial(); @Test public void testMath341(); public void checkPolynomial(PolynomialFunction p, String reference); private void checkNullPolynomial(PolynomialFunction p);
298121d9bcb9a87b99fdf5663d80802e2b15a1036cc84e4510599ee183b46ba2
[ "org.apache.commons.math3.analysis.polynomials.PolynomialFunctionTest::testfirstDerivativeComparison" ]
private static final long serialVersionUID = -7726511984200295583L; private final double coefficients[];
@Test public void testfirstDerivativeComparison()
protected double tolerance = 1e-12;
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.polynomials; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert; /** * Tests the PolynomialFunction implementation of a UnivariateFunction. * * @version $Id$ */ public final class PolynomialFunctionTest { /** Error tolerance for tests */ protected double tolerance = 1e-12; /** * tests the value of a constant polynomial. * * <p>value of this is 2.5 everywhere.</p> */ @Test public void testConstants() { double[] c = { 2.5 }; PolynomialFunction f = new PolynomialFunction(c); // verify that we are equal to c[0] at several (nonsymmetric) places Assert.assertEquals(f.value(0), c[0], tolerance); Assert.assertEquals(f.value(-1), c[0], tolerance); Assert.assertEquals(f.value(-123.5), c[0], tolerance); Assert.assertEquals(f.value(3), c[0], tolerance); Assert.assertEquals(f.value(456.89), c[0], tolerance); Assert.assertEquals(f.degree(), 0); Assert.assertEquals(f.derivative().value(0), 0, tolerance); Assert.assertEquals(f.polynomialDerivative().derivative().value(0), 0, tolerance); } /** * tests the value of a linear polynomial. * * <p>This will test the function f(x) = 3*x - 1.5</p> * <p>This will have the values * <tt>f(0) = -1.5, f(-1) = -4.5, f(-2.5) = -9, * f(0.5) = 0, f(1.5) = 3</tt> and <tt>f(3) = 7.5</tt> * </p> */ @Test public void testLinear() { double[] c = { -1.5, 3 }; PolynomialFunction f = new PolynomialFunction(c); // verify that we are equal to c[0] when x=0 Assert.assertEquals(f.value(0), c[0], tolerance); // now check a few other places Assert.assertEquals(-4.5, f.value(-1), tolerance); Assert.assertEquals(-9, f.value(-2.5), tolerance); Assert.assertEquals(0, f.value(0.5), tolerance); Assert.assertEquals(3, f.value(1.5), tolerance); Assert.assertEquals(7.5, f.value(3), tolerance); Assert.assertEquals(f.degree(), 1); Assert.assertEquals(f.polynomialDerivative().derivative().value(0), 0, tolerance); } /** * Tests a second order polynomial. * <p> This will test the function f(x) = 2x^2 - 3x -2 = (2x+1)(x-2)</p> */ @Test public void testQuadratic() { double[] c = { -2, -3, 2 }; PolynomialFunction f = new PolynomialFunction(c); // verify that we are equal to c[0] when x=0 Assert.assertEquals(f.value(0), c[0], tolerance); // now check a few other places Assert.assertEquals(0, f.value(-0.5), tolerance); Assert.assertEquals(0, f.value(2), tolerance); Assert.assertEquals(-2, f.value(1.5), tolerance); Assert.assertEquals(7, f.value(-1.5), tolerance); Assert.assertEquals(265.5312, f.value(12.34), tolerance); } /** * This will test the quintic function * f(x) = x^2(x-5)(x+3)(x-1) = x^5 - 3x^4 -13x^3 + 15x^2</p> */ @Test public void testQuintic() { double[] c = { 0, 0, 15, -13, -3, 1 }; PolynomialFunction f = new PolynomialFunction(c); // verify that we are equal to c[0] when x=0 Assert.assertEquals(f.value(0), c[0], tolerance); // now check a few other places Assert.assertEquals(0, f.value(5), tolerance); Assert.assertEquals(0, f.value(1), tolerance); Assert.assertEquals(0, f.value(-3), tolerance); Assert.assertEquals(54.84375, f.value(-1.5), tolerance); Assert.assertEquals(-8.06637, f.value(1.3), tolerance); Assert.assertEquals(f.degree(), 5); } /** * tests the firstDerivative function by comparison * * <p>This will test the functions * <tt>f(x) = x^3 - 2x^2 + 6x + 3, g(x) = 3x^2 - 4x + 6</tt> * and <tt>h(x) = 6x - 4</tt> */ @Test public void testfirstDerivativeComparison() { double[] f_coeff = { 3, 6, -2, 1 }; double[] g_coeff = { 6, -4, 3 }; double[] h_coeff = { -4, 6 }; PolynomialFunction f = new PolynomialFunction(f_coeff); PolynomialFunction g = new PolynomialFunction(g_coeff); PolynomialFunction h = new PolynomialFunction(h_coeff); // compare f' = g Assert.assertEquals(f.derivative().value(0), g.value(0), tolerance); Assert.assertEquals(f.derivative().value(1), g.value(1), tolerance); Assert.assertEquals(f.derivative().value(100), g.value(100), tolerance); Assert.assertEquals(f.derivative().value(4.1), g.value(4.1), tolerance); Assert.assertEquals(f.derivative().value(-3.25), g.value(-3.25), tolerance); // compare g' = h Assert.assertEquals(g.derivative().value(FastMath.PI), h.value(FastMath.PI), tolerance); Assert.assertEquals(g.derivative().value(FastMath.E), h.value(FastMath.E), tolerance); } @Test public void testString() { PolynomialFunction p = new PolynomialFunction(new double[] { -5, 3, 1 }); checkPolynomial(p, "-5 + 3 x + x^2"); checkPolynomial(new PolynomialFunction(new double[] { 0, -2, 3 }), "-2 x + 3 x^2"); checkPolynomial(new PolynomialFunction(new double[] { 1, -2, 3 }), "1 - 2 x + 3 x^2"); checkPolynomial(new PolynomialFunction(new double[] { 0, 2, 3 }), "2 x + 3 x^2"); checkPolynomial(new PolynomialFunction(new double[] { 1, 2, 3 }), "1 + 2 x + 3 x^2"); checkPolynomial(new PolynomialFunction(new double[] { 1, 0, 3 }), "1 + 3 x^2"); checkPolynomial(new PolynomialFunction(new double[] { 0 }), "0"); } @Test public void testAddition() { PolynomialFunction p1 = new PolynomialFunction(new double[] { -2, 1 }); PolynomialFunction p2 = new PolynomialFunction(new double[] { 2, -1, 0 }); checkNullPolynomial(p1.add(p2)); p2 = p1.add(p1); checkPolynomial(p2, "-4 + 2 x"); p1 = new PolynomialFunction(new double[] { 1, -4, 2 }); p2 = new PolynomialFunction(new double[] { -1, 3, -2 }); p1 = p1.add(p2); Assert.assertEquals(1, p1.degree()); checkPolynomial(p1, "-x"); } @Test public void testSubtraction() { PolynomialFunction p1 = new PolynomialFunction(new double[] { -2, 1 }); checkNullPolynomial(p1.subtract(p1)); PolynomialFunction p2 = new PolynomialFunction(new double[] { -2, 6 }); p2 = p2.subtract(p1); checkPolynomial(p2, "5 x"); p1 = new PolynomialFunction(new double[] { 1, -4, 2 }); p2 = new PolynomialFunction(new double[] { -1, 3, 2 }); p1 = p1.subtract(p2); Assert.assertEquals(1, p1.degree()); checkPolynomial(p1, "2 - 7 x"); } @Test public void testMultiplication() { PolynomialFunction p1 = new PolynomialFunction(new double[] { -3, 2 }); PolynomialFunction p2 = new PolynomialFunction(new double[] { 3, 2, 1 }); checkPolynomial(p1.multiply(p2), "-9 + x^2 + 2 x^3"); p1 = new PolynomialFunction(new double[] { 0, 1 }); p2 = p1; for (int i = 2; i < 10; ++i) { p2 = p2.multiply(p1); checkPolynomial(p2, "x^" + i); } } @Test public void testSerial() { PolynomialFunction p2 = new PolynomialFunction(new double[] { 3, 2, 1 }); Assert.assertEquals(p2, TestUtils.serializeAndRecover(p2)); } /** * tests the firstDerivative function by comparison * * <p>This will test the functions * <tt>f(x) = x^3 - 2x^2 + 6x + 3, g(x) = 3x^2 - 4x + 6</tt> * and <tt>h(x) = 6x - 4</tt> */ @Test public void testMath341() { double[] f_coeff = { 3, 6, -2, 1 }; double[] g_coeff = { 6, -4, 3 }; double[] h_coeff = { -4, 6 }; PolynomialFunction f = new PolynomialFunction(f_coeff); PolynomialFunction g = new PolynomialFunction(g_coeff); PolynomialFunction h = new PolynomialFunction(h_coeff); // compare f' = g Assert.assertEquals(f.derivative().value(0), g.value(0), tolerance); Assert.assertEquals(f.derivative().value(1), g.value(1), tolerance); Assert.assertEquals(f.derivative().value(100), g.value(100), tolerance); Assert.assertEquals(f.derivative().value(4.1), g.value(4.1), tolerance); Assert.assertEquals(f.derivative().value(-3.25), g.value(-3.25), tolerance); // compare g' = h Assert.assertEquals(g.derivative().value(FastMath.PI), h.value(FastMath.PI), tolerance); Assert.assertEquals(g.derivative().value(FastMath.E), h.value(FastMath.E), tolerance); } public void checkPolynomial(PolynomialFunction p, String reference) { Assert.assertEquals(reference, p.toString()); } private void checkNullPolynomial(PolynomialFunction p) { for (double coefficient : p.getCoefficients()) { Assert.assertEquals(0, coefficient, 1e-15); } } }
[ { "be_test_class_file": "org/apache/commons/math3/analysis/polynomials/PolynomialFunction.java", "be_test_class_name": "org.apache.commons.math3.analysis.polynomials.PolynomialFunction", "be_test_function_name": "derivative", "be_test_function_signature": "()Lorg/apache/commons/math3/analysis/UnivariateFunction;", "line_numbers": [ "290" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/analysis/polynomials/PolynomialFunction.java", "be_test_class_name": "org.apache.commons.math3.analysis.polynomials.PolynomialFunction", "be_test_function_name": "differentiate", "be_test_function_signature": "([D)[D", "line_numbers": [ "260", "261", "262", "263", "265", "266", "268", "269", "270", "272" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/apache/commons/math3/analysis/polynomials/PolynomialFunction.java", "be_test_class_name": "org.apache.commons.math3.analysis.polynomials.PolynomialFunction", "be_test_function_name": "evaluate", "be_test_function_signature": "([DD)D", "line_numbers": [ "130", "131", "132", "133", "135", "136", "137", "139" ], "method_line_rate": 0.875 }, { "be_test_class_file": "org/apache/commons/math3/analysis/polynomials/PolynomialFunction.java", "be_test_class_name": "org.apache.commons.math3.analysis.polynomials.PolynomialFunction", "be_test_function_name": "polynomialDerivative", "be_test_function_signature": "()Lorg/apache/commons/math3/analysis/polynomials/PolynomialFunction;", "line_numbers": [ "281" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/analysis/polynomials/PolynomialFunction.java", "be_test_class_name": "org.apache.commons.math3.analysis.polynomials.PolynomialFunction", "be_test_function_name": "value", "be_test_function_signature": "(D)D", "line_numbers": [ "94" ], "method_line_rate": 1 } ]
public class ComplexTest
@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); }
// 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_normal_fourthRoot` for the `Complex` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * 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> */
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,135
testNthRoot_normal_fourthRoot
```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_normal_fourthRoot` for the `Complex` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * 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> */
1,115
// 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_normal_fourthRoot` for the `Complex` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * 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() {
/** * 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> */
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_normal_fourthRoot` for the `Complex` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * 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() { ```
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);
29cbcca886b70f129fc901148556390f202fc2d5777a88d5eb7c83b20885610d
[ "org.apache.commons.math3.complex.ComplexTest::testNthRoot_normal_fourthRoot" ]
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_normal_fourthRoot()
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 BoundedIteratorTest<E> extends AbstractIteratorTest<E>
@Test public void testRemoveUnsupported() { Iterator<E> mockIterator = new AbstractIteratorDecorator<E>(testList.iterator()) { @Override public void remove() { throw new UnsupportedOperationException(); } }; Iterator<E> iter = new BoundedIterator<E>(mockIterator, 1, 5); assertTrue(iter.hasNext()); assertEquals("b", iter.next()); try { iter.remove(); fail("Expected UnsupportedOperationException."); } catch (UnsupportedOperationException usoe) { /* Success case */ } }
// // Abstract Java Tested Class // package org.apache.commons.collections4.iterators; // // import java.util.Iterator; // import java.util.NoSuchElementException; // // // // public class BoundedIterator<E> implements Iterator<E> { // private final Iterator<? extends E> iterator; // private final long offset; // private final long max; // private long pos; // // public BoundedIterator(final Iterator<? extends E> iterator, final long offset, final long max); // private void init(); // @Override // public boolean hasNext(); // private boolean checkBounds(); // @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 BoundedIteratorTest<E> extends AbstractIteratorTest<E> { // private final String[] testArray = { // "a", "b", "c", "d", "e", "f", "g" // }; // private List<E> testList; // // public BoundedIteratorTest(final String testName); // @SuppressWarnings("unchecked") // @Override // public void setUp() // throws Exception; // @Override // public Iterator<E> makeEmptyIterator(); // @Override // public Iterator<E> makeObject(); // @Test // public void testBounded(); // @Test // public void testSameAsDecorated(); // @Test // public void testEmptyBounded(); // @Test // public void testNegativeOffset(); // @Test // public void testNegativeMax(); // @Test // public void testOffsetGreaterThanSize(); // @Test // public void testMaxGreaterThanSize(); // @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 `testRemoveUnsupported` for the `BoundedIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test the case if the decorated iterator does not support the * <code>remove()</code> method and throws an {@link UnsupportedOperationException}. */
src/test/java/org/apache/commons/collections4/iterators/BoundedIteratorTest.java
package org.apache.commons.collections4.iterators; import java.util.Iterator; import java.util.NoSuchElementException;
public BoundedIterator(final Iterator<? extends E> iterator, final long offset, final long max); private void init(); @Override public boolean hasNext(); private boolean checkBounds(); @Override public E next(); @Override public void remove();
369
testRemoveUnsupported
```java // Abstract Java Tested Class package org.apache.commons.collections4.iterators; import java.util.Iterator; import java.util.NoSuchElementException; public class BoundedIterator<E> implements Iterator<E> { private final Iterator<? extends E> iterator; private final long offset; private final long max; private long pos; public BoundedIterator(final Iterator<? extends E> iterator, final long offset, final long max); private void init(); @Override public boolean hasNext(); private boolean checkBounds(); @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 BoundedIteratorTest<E> extends AbstractIteratorTest<E> { private final String[] testArray = { "a", "b", "c", "d", "e", "f", "g" }; private List<E> testList; public BoundedIteratorTest(final String testName); @SuppressWarnings("unchecked") @Override public void setUp() throws Exception; @Override public Iterator<E> makeEmptyIterator(); @Override public Iterator<E> makeObject(); @Test public void testBounded(); @Test public void testSameAsDecorated(); @Test public void testEmptyBounded(); @Test public void testNegativeOffset(); @Test public void testNegativeMax(); @Test public void testOffsetGreaterThanSize(); @Test public void testMaxGreaterThanSize(); @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 `testRemoveUnsupported` for the `BoundedIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test the case if the decorated iterator does not support the * <code>remove()</code> method and throws an {@link UnsupportedOperationException}. */
352
// // Abstract Java Tested Class // package org.apache.commons.collections4.iterators; // // import java.util.Iterator; // import java.util.NoSuchElementException; // // // // public class BoundedIterator<E> implements Iterator<E> { // private final Iterator<? extends E> iterator; // private final long offset; // private final long max; // private long pos; // // public BoundedIterator(final Iterator<? extends E> iterator, final long offset, final long max); // private void init(); // @Override // public boolean hasNext(); // private boolean checkBounds(); // @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 BoundedIteratorTest<E> extends AbstractIteratorTest<E> { // private final String[] testArray = { // "a", "b", "c", "d", "e", "f", "g" // }; // private List<E> testList; // // public BoundedIteratorTest(final String testName); // @SuppressWarnings("unchecked") // @Override // public void setUp() // throws Exception; // @Override // public Iterator<E> makeEmptyIterator(); // @Override // public Iterator<E> makeObject(); // @Test // public void testBounded(); // @Test // public void testSameAsDecorated(); // @Test // public void testEmptyBounded(); // @Test // public void testNegativeOffset(); // @Test // public void testNegativeMax(); // @Test // public void testOffsetGreaterThanSize(); // @Test // public void testMaxGreaterThanSize(); // @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 `testRemoveUnsupported` for the `BoundedIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test the case if the decorated iterator does not support the * <code>remove()</code> method and throws an {@link UnsupportedOperationException}. */ @Test public void testRemoveUnsupported() {
/** * Test the case if the decorated iterator does not support the * <code>remove()</code> method and throws an {@link UnsupportedOperationException}. */
28
org.apache.commons.collections4.iterators.BoundedIterator
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.collections4.iterators; import java.util.Iterator; import java.util.NoSuchElementException; public class BoundedIterator<E> implements Iterator<E> { private final Iterator<? extends E> iterator; private final long offset; private final long max; private long pos; public BoundedIterator(final Iterator<? extends E> iterator, final long offset, final long max); private void init(); @Override public boolean hasNext(); private boolean checkBounds(); @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 BoundedIteratorTest<E> extends AbstractIteratorTest<E> { private final String[] testArray = { "a", "b", "c", "d", "e", "f", "g" }; private List<E> testList; public BoundedIteratorTest(final String testName); @SuppressWarnings("unchecked") @Override public void setUp() throws Exception; @Override public Iterator<E> makeEmptyIterator(); @Override public Iterator<E> makeObject(); @Test public void testBounded(); @Test public void testSameAsDecorated(); @Test public void testEmptyBounded(); @Test public void testNegativeOffset(); @Test public void testNegativeMax(); @Test public void testOffsetGreaterThanSize(); @Test public void testMaxGreaterThanSize(); @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 `testRemoveUnsupported` for the `BoundedIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test the case if the decorated iterator does not support the * <code>remove()</code> method and throws an {@link UnsupportedOperationException}. */ @Test public void testRemoveUnsupported() { ```
public class BoundedIterator<E> implements Iterator<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 BoundedIteratorTest(final String testName); @SuppressWarnings("unchecked") @Override public void setUp() throws Exception; @Override public Iterator<E> makeEmptyIterator(); @Override public Iterator<E> makeObject(); @Test public void testBounded(); @Test public void testSameAsDecorated(); @Test public void testEmptyBounded(); @Test public void testNegativeOffset(); @Test public void testNegativeMax(); @Test public void testOffsetGreaterThanSize(); @Test public void testMaxGreaterThanSize(); @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();
29f36cde95782c74a87f5e3d990cc2d1a5c29b424f4dc369b7a66b33153b1fe9
[ "org.apache.commons.collections4.iterators.BoundedIteratorTest::testRemoveUnsupported" ]
private final Iterator<? extends E> iterator; private final long offset; private final long max; private long pos;
@Test public void testRemoveUnsupported()
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 BoundedIterator}. * * @version $Id$ */ public class BoundedIteratorTest<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 BoundedIteratorTest(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 BoundedIterator<E>(Collections.<E>emptyList().iterator(), 0, 10); } @Override public Iterator<E> makeObject() { return new BoundedIterator<E>(new ArrayList<E>(testList).iterator(), 1, testList.size() - 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 testBounded() { Iterator<E> iter = new BoundedIterator<E>(testList.iterator(), 2, 4); 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()); 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 and the <code>max</code> is its size, in that the BoundedIterator * should return all the same elements as its decorated iterator. */ @Test public void testSameAsDecorated() { Iterator<E> iter = new BoundedIterator<E>(testList.iterator(), 0, testList.size()); 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 a decorated iterator bounded to a <code>max</code> of 0. The * BoundedIterator should behave as if there are no more elements to return, * since it is technically an empty iterator. */ @Test public void testEmptyBounded() { Iterator<E> iter = new BoundedIterator<E>(testList.iterator(), 3, 0); 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 BoundedIterator<E>(testList.iterator(), -1, 4); fail("Expected IllegalArgumentException."); } catch (IllegalArgumentException iae) { /* Success case */ } } /** * Test the case if a negative <code>max</code> is passed to the * constructor. {@link IllegalArgumentException} is expected. */ @Test public void testNegativeMax() { try { new BoundedIterator<E>(testList.iterator(), 3, -1); fail("Expected IllegalArgumentException."); } catch (IllegalArgumentException iae) { /* Success case */ } } /** * Test the case if the <code>offset</code> passed to the constructor is * greater than the decorated iterator's size. The BoundedIterator should * behave as if there are no more elements to return. */ @Test public void testOffsetGreaterThanSize() { Iterator<E> iter = new BoundedIterator<E>(testList.iterator(), 10, 4); assertFalse(iter.hasNext()); try { iter.next(); fail("Expected NoSuchElementException."); } catch (NoSuchElementException nsee) { /* Success case */ } } /** * Test the case if the <code>max</code> passed to the constructor is * greater than the size of the decorated iterator. The last element * returned should be the same as the last element of the decorated * iterator. */ @Test public void testMaxGreaterThanSize() { Iterator<E> iter = new BoundedIterator<E>(testList.iterator(), 1, 10); 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 <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 BoundedIterator<E>(testListCopy.iterator(), 1, 5); 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 BoundedIterator<E>(testListCopy.iterator(), 1, 5); 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 BoundedIterator<E>(testListCopy.iterator(), 1, 5); assertTrue(iter.hasNext()); assertEquals("b", iter.next()); iter.remove(); assertFalse(testListCopy.contains("b")); 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()); 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 BoundedIterator<E>(testListCopy.iterator(), 1, 5); assertTrue(iter.hasNext()); assertEquals("b", iter.next()); assertTrue(iter.hasNext()); assertEquals("c", iter.next()); 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()); 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 BoundedIterator<E>(testListCopy.iterator(), 1, 5); 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()); assertFalse(iter.hasNext()); try { iter.next(); fail("Expected NoSuchElementException."); } catch (NoSuchElementException nsee) { /* Success case */ } iter.remove(); assertFalse(testListCopy.contains("f")); 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 BoundedIterator<E>(mockIterator, 1, 5); 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/BoundedIterator.java", "be_test_class_name": "org.apache.commons.collections4.iterators.BoundedIterator", "be_test_function_name": "checkBounds", "be_test_function_signature": "()Z", "line_numbers": [ "106", "107", "109" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "org/apache/commons/collections4/iterators/BoundedIterator.java", "be_test_class_name": "org.apache.commons.collections4.iterators.BoundedIterator", "be_test_function_name": "hasNext", "be_test_function_signature": "()Z", "line_numbers": [ "95", "96", "98" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "org/apache/commons/collections4/iterators/BoundedIterator.java", "be_test_class_name": "org.apache.commons.collections4.iterators.BoundedIterator", "be_test_function_name": "init", "be_test_function_signature": "()V", "line_numbers": [ "85", "86", "87", "89" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/collections4/iterators/BoundedIterator.java", "be_test_class_name": "org.apache.commons.collections4.iterators.BoundedIterator", "be_test_function_name": "next", "be_test_function_signature": "()Ljava/lang/Object;", "line_numbers": [ "114", "115", "117", "118", "119" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/apache/commons/collections4/iterators/BoundedIterator.java", "be_test_class_name": "org.apache.commons.collections4.iterators.BoundedIterator", "be_test_function_name": "remove", "be_test_function_signature": "()V", "line_numbers": [ "132", "133", "135", "136" ], "method_line_rate": 0.5 } ]
public class PearsonsCorrelationTest
@Test public void testCovarianceConsistency() { RealMatrix matrix = createRealMatrix(longleyData, 16, 7); PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); Covariance covInstance = new Covariance(matrix); PearsonsCorrelation corrFromCovInstance = new PearsonsCorrelation(covInstance); TestUtils.assertEquals("correlation values", corrInstance.getCorrelationMatrix(), corrFromCovInstance.getCorrelationMatrix(), 10E-15); TestUtils.assertEquals("p values", corrInstance.getCorrelationPValues(), corrFromCovInstance.getCorrelationPValues(), 10E-15); TestUtils.assertEquals("standard errors", corrInstance.getCorrelationStandardErrors(), corrFromCovInstance.getCorrelationStandardErrors(), 10E-15); PearsonsCorrelation corrFromCovInstance2 = new PearsonsCorrelation(covInstance.getCovarianceMatrix(), 16); TestUtils.assertEquals("correlation values", corrInstance.getCorrelationMatrix(), corrFromCovInstance2.getCorrelationMatrix(), 10E-15); TestUtils.assertEquals("p values", corrInstance.getCorrelationPValues(), corrFromCovInstance2.getCorrelationPValues(), 10E-15); TestUtils.assertEquals("standard errors", corrInstance.getCorrelationStandardErrors(), corrFromCovInstance2.getCorrelationStandardErrors(), 10E-15); }
// 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 // }; // protected final double[] swissData = 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 // }; // // @Test // public void testLongly(); // @Test // public void testSwissFertility(); // @Test // public void testPValueNearZero(); // @Test // public void testConstant(); // @Test // public void testInsufficientData(); // @Test // public void testStdErrorConsistency(); // @Test // public void testCovarianceConsistency(); // @Test // public void testConsistency(); // protected RealMatrix createRealMatrix(double[] data, int nRows, int nCols); // protected RealMatrix createLowerTriangularRealMatrix(double[] data, int dimension); // protected void fillUpper(RealMatrix matrix, double diagonalValue); // } // You are a professional Java test case writer, please create a test case named `testCovarianceConsistency` for the `PearsonsCorrelation` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Verify that creating correlation from covariance gives same results as * direct computation from the original matrix */
src/test/java/org/apache/commons/math3/stat/correlation/PearsonsCorrelationTest.java
package org.apache.commons.math3.stat.correlation; import org.apache.commons.math3.distribution.TDistribution; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.BlockRealMatrix; import org.apache.commons.math3.stat.regression.SimpleRegression; import org.apache.commons.math3.util.FastMath;
public PearsonsCorrelation(); public PearsonsCorrelation(double[][] data); public PearsonsCorrelation(RealMatrix matrix); public PearsonsCorrelation(Covariance covariance); public PearsonsCorrelation(RealMatrix covarianceMatrix, int numberOfObservations); public RealMatrix getCorrelationMatrix(); public RealMatrix getCorrelationStandardErrors(); public RealMatrix getCorrelationPValues(); public RealMatrix computeCorrelationMatrix(RealMatrix matrix); public RealMatrix computeCorrelationMatrix(double[][] data); public double correlation(final double[] xArray, final double[] yArray); public RealMatrix covarianceToCorrelation(RealMatrix covarianceMatrix); private void checkSufficientData(final RealMatrix matrix);
268
testCovarianceConsistency
```java 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 }; protected final double[] swissData = 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 }; @Test public void testLongly(); @Test public void testSwissFertility(); @Test public void testPValueNearZero(); @Test public void testConstant(); @Test public void testInsufficientData(); @Test public void testStdErrorConsistency(); @Test public void testCovarianceConsistency(); @Test public void testConsistency(); protected RealMatrix createRealMatrix(double[] data, int nRows, int nCols); protected RealMatrix createLowerTriangularRealMatrix(double[] data, int dimension); protected void fillUpper(RealMatrix matrix, double diagonalValue); } ``` You are a professional Java test case writer, please create a test case named `testCovarianceConsistency` for the `PearsonsCorrelation` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Verify that creating correlation from covariance gives same results as * direct computation from the original matrix */
247
// 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 // }; // protected final double[] swissData = 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 // }; // // @Test // public void testLongly(); // @Test // public void testSwissFertility(); // @Test // public void testPValueNearZero(); // @Test // public void testConstant(); // @Test // public void testInsufficientData(); // @Test // public void testStdErrorConsistency(); // @Test // public void testCovarianceConsistency(); // @Test // public void testConsistency(); // protected RealMatrix createRealMatrix(double[] data, int nRows, int nCols); // protected RealMatrix createLowerTriangularRealMatrix(double[] data, int dimension); // protected void fillUpper(RealMatrix matrix, double diagonalValue); // } // You are a professional Java test case writer, please create a test case named `testCovarianceConsistency` for the `PearsonsCorrelation` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Verify that creating correlation from covariance gives same results as * direct computation from the original matrix */ @Test public void testCovarianceConsistency() {
/** * Verify that creating correlation from covariance gives same results as * direct computation from the original matrix */
1
org.apache.commons.math3.stat.correlation.PearsonsCorrelation
src/test/java
```java 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 }; protected final double[] swissData = 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 }; @Test public void testLongly(); @Test public void testSwissFertility(); @Test public void testPValueNearZero(); @Test public void testConstant(); @Test public void testInsufficientData(); @Test public void testStdErrorConsistency(); @Test public void testCovarianceConsistency(); @Test public void testConsistency(); protected RealMatrix createRealMatrix(double[] data, int nRows, int nCols); protected RealMatrix createLowerTriangularRealMatrix(double[] data, int dimension); protected void fillUpper(RealMatrix matrix, double diagonalValue); } ``` You are a professional Java test case writer, please create a test case named `testCovarianceConsistency` for the `PearsonsCorrelation` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Verify that creating correlation from covariance gives same results as * direct computation from the original matrix */ @Test public void testCovarianceConsistency() { ```
public class PearsonsCorrelation
package org.apache.commons.math3.stat.correlation; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.distribution.TDistribution; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.BlockRealMatrix; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test;
@Test public void testLongly(); @Test public void testSwissFertility(); @Test public void testPValueNearZero(); @Test public void testConstant(); @Test public void testInsufficientData(); @Test public void testStdErrorConsistency(); @Test public void testCovarianceConsistency(); @Test public void testConsistency(); protected RealMatrix createRealMatrix(double[] data, int nRows, int nCols); protected RealMatrix createLowerTriangularRealMatrix(double[] data, int dimension); protected void fillUpper(RealMatrix matrix, double diagonalValue);
2bb7201a73970cc331c82e1cdf9d80272ab9c6b3fe6a01ee57b3a862bbc5a22a
[ "org.apache.commons.math3.stat.correlation.PearsonsCorrelationTest::testCovarianceConsistency" ]
private final RealMatrix correlationMatrix; private final int nObs;
@Test public void testCovarianceConsistency()
protected final double[] longleyData = 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 }; protected final double[] swissData = 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 };
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.correlation; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.distribution.TDistribution; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.BlockRealMatrix; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; public class PearsonsCorrelationTest { protected final double[] longleyData = 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 }; protected final double[] swissData = 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 }; /** * Test Longley dataset against R. */ @Test public void testLongly() { RealMatrix matrix = createRealMatrix(longleyData, 16, 7); PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); RealMatrix correlationMatrix = corrInstance.getCorrelationMatrix(); double[] rData = new double[] { 1.000000000000000, 0.9708985250610560, 0.9835516111796693, 0.5024980838759942, 0.4573073999764817, 0.960390571594376, 0.9713294591921188, 0.970898525061056, 1.0000000000000000, 0.9915891780247822, 0.6206333925590966, 0.4647441876006747, 0.979163432977498, 0.9911491900672053, 0.983551611179669, 0.9915891780247822, 1.0000000000000000, 0.6042609398895580, 0.4464367918926265, 0.991090069458478, 0.9952734837647849, 0.502498083875994, 0.6206333925590966, 0.6042609398895580, 1.0000000000000000, -0.1774206295018783, 0.686551516365312, 0.6682566045621746, 0.457307399976482, 0.4647441876006747, 0.4464367918926265, -0.1774206295018783, 1.0000000000000000, 0.364416267189032, 0.4172451498349454, 0.960390571594376, 0.9791634329774981, 0.9910900694584777, 0.6865515163653120, 0.3644162671890320, 1.000000000000000, 0.9939528462329257, 0.971329459192119, 0.9911491900672053, 0.9952734837647849, 0.6682566045621746, 0.4172451498349454, 0.993952846232926, 1.0000000000000000 }; TestUtils.assertEquals("correlation matrix", createRealMatrix(rData, 7, 7), correlationMatrix, 10E-15); double[] rPvalues = new double[] { 4.38904690369668e-10, 8.36353208910623e-12, 7.8159700933611e-14, 0.0472894097790304, 0.01030636128354301, 0.01316878049026582, 0.0749178049642416, 0.06971758330341182, 0.0830166169296545, 0.510948586323452, 3.693245043123738e-09, 4.327782576751815e-11, 1.167954621905665e-13, 0.00331028281967516, 0.1652293725106684, 3.95834476307755e-10, 1.114663916723657e-13, 1.332267629550188e-15, 0.00466039138541463, 0.1078477071581498, 7.771561172376096e-15 }; RealMatrix rPMatrix = createLowerTriangularRealMatrix(rPvalues, 7); fillUpper(rPMatrix, 0d); TestUtils.assertEquals("correlation p values", rPMatrix, corrInstance.getCorrelationPValues(), 10E-15); } /** * Test R Swiss fertility dataset against R. */ @Test public void testSwissFertility() { RealMatrix matrix = createRealMatrix(swissData, 47, 5); PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); RealMatrix correlationMatrix = corrInstance.getCorrelationMatrix(); double[] rData = new double[] { 1.0000000000000000, 0.3530791836199747, -0.6458827064572875, -0.6637888570350691, 0.4636847006517939, 0.3530791836199747, 1.0000000000000000,-0.6865422086171366, -0.6395225189483201, 0.4010950530487398, -0.6458827064572875, -0.6865422086171366, 1.0000000000000000, 0.6984152962884830, -0.5727418060641666, -0.6637888570350691, -0.6395225189483201, 0.6984152962884830, 1.0000000000000000, -0.1538589170909148, 0.4636847006517939, 0.4010950530487398, -0.5727418060641666, -0.1538589170909148, 1.0000000000000000 }; TestUtils.assertEquals("correlation matrix", createRealMatrix(rData, 5, 5), correlationMatrix, 10E-15); double[] rPvalues = new double[] { 0.01491720061472623, 9.45043734069043e-07, 9.95151527133974e-08, 3.658616965962355e-07, 1.304590105694471e-06, 4.811397236181847e-08, 0.001028523190118147, 0.005204433539191644, 2.588307925380906e-05, 0.301807756132683 }; RealMatrix rPMatrix = createLowerTriangularRealMatrix(rPvalues, 5); fillUpper(rPMatrix, 0d); TestUtils.assertEquals("correlation p values", rPMatrix, corrInstance.getCorrelationPValues(), 10E-15); } /** * Test p-value near 0. JIRA: MATH-371 */ @Test public void testPValueNearZero() { /* * Create a dataset that has r -> 1, p -> 0 as dimension increases. * Prior to the fix for MATH-371, p vanished for dimension >= 14. * Post fix, p-values diminish smoothly, vanishing at dimension = 127. * Tested value is ~1E-303. */ int dimension = 120; double[][] data = new double[dimension][2]; for (int i = 0; i < dimension; i++) { data[i][0] = i; data[i][1] = i + 1/((double)i + 1); } PearsonsCorrelation corrInstance = new PearsonsCorrelation(data); Assert.assertTrue(corrInstance.getCorrelationPValues().getEntry(0, 1) > 0); } /** * Constant column */ @Test public void testConstant() { double[] noVariance = new double[] {1, 1, 1, 1}; double[] values = new double[] {1, 2, 3, 4}; Assert.assertTrue(Double.isNaN(new PearsonsCorrelation().correlation(noVariance, values))); } /** * Insufficient data */ @Test public void testInsufficientData() { double[] one = new double[] {1}; double[] two = new double[] {2}; try { new PearsonsCorrelation().correlation(one, two); Assert.fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // Expected } RealMatrix matrix = new BlockRealMatrix(new double[][] {{0},{1}}); try { new PearsonsCorrelation(matrix); Assert.fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // Expected } } /** * Verify that direct t-tests using standard error estimates are consistent * with reported p-values */ @Test public void testStdErrorConsistency() { TDistribution tDistribution = new TDistribution(45); RealMatrix matrix = createRealMatrix(swissData, 47, 5); PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); RealMatrix rValues = corrInstance.getCorrelationMatrix(); RealMatrix pValues = corrInstance.getCorrelationPValues(); RealMatrix stdErrors = corrInstance.getCorrelationStandardErrors(); for (int i = 0; i < 5; i++) { for (int j = 0; j < i; j++) { double t = FastMath.abs(rValues.getEntry(i, j)) / stdErrors.getEntry(i, j); double p = 2 * (1 - tDistribution.cumulativeProbability(t)); Assert.assertEquals(p, pValues.getEntry(i, j), 10E-15); } } } /** * Verify that creating correlation from covariance gives same results as * direct computation from the original matrix */ @Test public void testCovarianceConsistency() { RealMatrix matrix = createRealMatrix(longleyData, 16, 7); PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); Covariance covInstance = new Covariance(matrix); PearsonsCorrelation corrFromCovInstance = new PearsonsCorrelation(covInstance); TestUtils.assertEquals("correlation values", corrInstance.getCorrelationMatrix(), corrFromCovInstance.getCorrelationMatrix(), 10E-15); TestUtils.assertEquals("p values", corrInstance.getCorrelationPValues(), corrFromCovInstance.getCorrelationPValues(), 10E-15); TestUtils.assertEquals("standard errors", corrInstance.getCorrelationStandardErrors(), corrFromCovInstance.getCorrelationStandardErrors(), 10E-15); PearsonsCorrelation corrFromCovInstance2 = new PearsonsCorrelation(covInstance.getCovarianceMatrix(), 16); TestUtils.assertEquals("correlation values", corrInstance.getCorrelationMatrix(), corrFromCovInstance2.getCorrelationMatrix(), 10E-15); TestUtils.assertEquals("p values", corrInstance.getCorrelationPValues(), corrFromCovInstance2.getCorrelationPValues(), 10E-15); TestUtils.assertEquals("standard errors", corrInstance.getCorrelationStandardErrors(), corrFromCovInstance2.getCorrelationStandardErrors(), 10E-15); } @Test public void testConsistency() { RealMatrix matrix = createRealMatrix(longleyData, 16, 7); PearsonsCorrelation corrInstance = new PearsonsCorrelation(matrix); double[][] data = matrix.getData(); double[] x = matrix.getColumn(0); double[] y = matrix.getColumn(1); Assert.assertEquals(new PearsonsCorrelation().correlation(x, y), corrInstance.getCorrelationMatrix().getEntry(0, 1), Double.MIN_VALUE); TestUtils.assertEquals("Correlation matrix", corrInstance.getCorrelationMatrix(), new PearsonsCorrelation().computeCorrelationMatrix(data), Double.MIN_VALUE); } protected RealMatrix createRealMatrix(double[] data, int nRows, int nCols) { double[][] matrixData = new double[nRows][nCols]; int ptr = 0; for (int i = 0; i < nRows; i++) { System.arraycopy(data, ptr, matrixData[i], 0, nCols); ptr += nCols; } return new BlockRealMatrix(matrixData); } protected RealMatrix createLowerTriangularRealMatrix(double[] data, int dimension) { int ptr = 0; RealMatrix result = new BlockRealMatrix(dimension, dimension); for (int i = 1; i < dimension; i++) { for (int j = 0; j < i; j++) { result.setEntry(i, j, data[ptr]); ptr++; } } return result; } protected void fillUpper(RealMatrix matrix, double diagonalValue) { int dimension = matrix.getColumnDimension(); for (int i = 0; i < dimension; i++) { matrix.setEntry(i, i, diagonalValue); for (int j = i+1; j < dimension; j++) { matrix.setEntry(i, j, matrix.getEntry(j, i)); } } } }
[ { "be_test_class_file": "org/apache/commons/math3/stat/correlation/PearsonsCorrelation.java", "be_test_class_name": "org.apache.commons.math3.stat.correlation.PearsonsCorrelation", "be_test_function_name": "checkSufficientData", "be_test_function_signature": "(Lorg/apache/commons/math3/linear/RealMatrix;)V", "line_numbers": [ "277", "278", "279", "280", "283" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/apache/commons/math3/stat/correlation/PearsonsCorrelation.java", "be_test_class_name": "org.apache.commons.math3.stat.correlation.PearsonsCorrelation", "be_test_function_name": "computeCorrelationMatrix", "be_test_function_signature": "(Lorg/apache/commons/math3/linear/RealMatrix;)Lorg/apache/commons/math3/linear/RealMatrix;", "line_numbers": [ "190", "191", "192", "193", "194", "195", "196", "198", "200" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/stat/correlation/PearsonsCorrelation.java", "be_test_class_name": "org.apache.commons.math3.stat.correlation.PearsonsCorrelation", "be_test_function_name": "correlation", "be_test_function_signature": "([D[D)D", "line_numbers": [ "228", "229", "230", "231", "232", "235", "236", "238" ], "method_line_rate": 0.75 }, { "be_test_class_file": "org/apache/commons/math3/stat/correlation/PearsonsCorrelation.java", "be_test_class_name": "org.apache.commons.math3.stat.correlation.PearsonsCorrelation", "be_test_function_name": "covarianceToCorrelation", "be_test_function_signature": "(Lorg/apache/commons/math3/linear/RealMatrix;)Lorg/apache/commons/math3/linear/RealMatrix;", "line_numbers": [ "254", "255", "256", "257", "258", "259", "260", "262", "263", "266" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/stat/correlation/PearsonsCorrelation.java", "be_test_class_name": "org.apache.commons.math3.stat.correlation.PearsonsCorrelation", "be_test_function_name": "getCorrelationMatrix", "be_test_function_signature": "()Lorg/apache/commons/math3/linear/RealMatrix;", "line_numbers": [ "122" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/stat/correlation/PearsonsCorrelation.java", "be_test_class_name": "org.apache.commons.math3.stat.correlation.PearsonsCorrelation", "be_test_function_name": "getCorrelationPValues", "be_test_function_signature": "()Lorg/apache/commons/math3/linear/RealMatrix;", "line_numbers": [ "164", "165", "166", "167", "168", "169", "170", "172", "173", "174", "178" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/stat/correlation/PearsonsCorrelation.java", "be_test_class_name": "org.apache.commons.math3.stat.correlation.PearsonsCorrelation", "be_test_function_name": "getCorrelationStandardErrors", "be_test_function_signature": "()Lorg/apache/commons/math3/linear/RealMatrix;", "line_numbers": [ "138", "139", "140", "141", "142", "143", "146" ], "method_line_rate": 1 } ]
public class PeriodAxisTests extends TestCase implements AxisChangeListener
public void testEqualsWithLocale() { PeriodAxis a1 = new PeriodAxis("Test", new Year(2000), new Year(2009), TimeZone.getDefault(), Locale.JAPAN); PeriodAxis a2 = new PeriodAxis("Test", new Year(2000), new Year(2009), TimeZone.getDefault(), Locale.JAPAN); assertTrue(a1.equals(a2)); assertTrue(a2.equals(a1)); a1 = new PeriodAxis("Test", new Year(2000), new Year(2009), TimeZone.getDefault(), Locale.UK); assertFalse(a1.equals(a2)); a2 = new PeriodAxis("Test", new Year(2000), new Year(2009), TimeZone.getDefault(), Locale.UK); assertTrue(a1.equals(a2)); }
// private transient Paint minorTickMarkPaint = Color.black; // private PeriodAxisLabelInfo[] labelInfo; // // public PeriodAxis(String label); // public PeriodAxis(String label, // RegularTimePeriod first, RegularTimePeriod last); // public PeriodAxis(String label, RegularTimePeriod first, // RegularTimePeriod last, TimeZone timeZone, Locale locale); // public RegularTimePeriod getFirst(); // public void setFirst(RegularTimePeriod first); // public RegularTimePeriod getLast(); // public void setLast(RegularTimePeriod last); // public TimeZone getTimeZone(); // public void setTimeZone(TimeZone zone); // public Locale getLocale(); // public Class getAutoRangeTimePeriodClass(); // public void setAutoRangeTimePeriodClass(Class c); // public Class getMajorTickTimePeriodClass(); // public void setMajorTickTimePeriodClass(Class c); // public boolean isMinorTickMarksVisible(); // public void setMinorTickMarksVisible(boolean visible); // public Class getMinorTickTimePeriodClass(); // public void setMinorTickTimePeriodClass(Class c); // public Stroke getMinorTickMarkStroke(); // public void setMinorTickMarkStroke(Stroke stroke); // public Paint getMinorTickMarkPaint(); // public void setMinorTickMarkPaint(Paint paint); // public float getMinorTickMarkInsideLength(); // public void setMinorTickMarkInsideLength(float length); // public float getMinorTickMarkOutsideLength(); // public void setMinorTickMarkOutsideLength(float length); // public PeriodAxisLabelInfo[] getLabelInfo(); // public void setLabelInfo(PeriodAxisLabelInfo[] info); // public Range getRange(); // public void setRange(Range range, boolean turnOffAutoRange, // boolean notify); // public void configure(); // public AxisSpace reserveSpace(Graphics2D g2, Plot plot, // Rectangle2D plotArea, RectangleEdge edge, // AxisSpace space); // public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, // Rectangle2D dataArea, RectangleEdge edge, // PlotRenderingInfo plotState); // protected void drawTickMarks(Graphics2D g2, AxisState state, // Rectangle2D dataArea, // RectangleEdge edge); // protected void drawTickMarksHorizontal(Graphics2D g2, AxisState state, // Rectangle2D dataArea, // RectangleEdge edge); // protected void drawTickMarksVertical(Graphics2D g2, AxisState state, // Rectangle2D dataArea, // RectangleEdge edge); // protected AxisState drawTickLabels(int band, Graphics2D g2, AxisState state, // Rectangle2D dataArea, // RectangleEdge edge); // public List refreshTicks(Graphics2D g2, AxisState state, // Rectangle2D dataArea, RectangleEdge edge); // public double valueToJava2D(double value, Rectangle2D area, // RectangleEdge edge); // public double java2DToValue(double java2DValue, Rectangle2D area, // RectangleEdge edge); // protected void autoAdjustRange(); // public boolean equals(Object obj); // public int hashCode(); // public Object clone() throws CloneNotSupportedException; // private RegularTimePeriod createInstance(Class periodClass, // Date millisecond, TimeZone zone, Locale locale); // private void writeObject(ObjectOutputStream stream) throws IOException; // private void readObject(ObjectInputStream stream) // throws IOException, ClassNotFoundException; // } // // // Abstract Java Test Class // package org.jfree.chart.axis.junit; // // import java.awt.BasicStroke; // import java.awt.Color; // import java.awt.Stroke; // 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.GregorianCalendar; // import java.util.Locale; // import java.util.SimpleTimeZone; // import java.util.TimeZone; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.chart.axis.PeriodAxis; // import org.jfree.chart.axis.PeriodAxisLabelInfo; // import org.jfree.chart.event.AxisChangeEvent; // import org.jfree.chart.event.AxisChangeListener; // import org.jfree.data.Range; // import org.jfree.data.time.DateRange; // import org.jfree.data.time.Day; // import org.jfree.data.time.Minute; // import org.jfree.data.time.Month; // import org.jfree.data.time.Quarter; // import org.jfree.data.time.Second; // import org.jfree.data.time.Year; // // // // public class PeriodAxisTests extends TestCase implements AxisChangeListener { // private AxisChangeEvent lastEvent; // private static final double EPSILON = 0.0000000001; // // public void axisChanged(AxisChangeEvent event); // public static Test suite(); // public PeriodAxisTests(String name); // public void testEquals(); // public void testEqualsWithLocale(); // public void testHashCode(); // public void testCloning(); // public void testSerialization(); // public void test1932146(); // public void test2490803(); // } // You are a professional Java test case writer, please create a test case named `testEqualsWithLocale` for the `PeriodAxis` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Confirm that the equals() method can distinguish the locale field (which * is new in version 1.0.13). */
tests/org/jfree/chart/axis/junit/PeriodAxisTests.java
package org.jfree.chart.axis; import java.awt.BasicStroke; import java.awt.Color; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.Constructor; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; 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.text.TextUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.util.RectangleEdge; import org.jfree.chart.util.SerialUtilities; import org.jfree.data.Range; import org.jfree.data.time.Day; import org.jfree.data.time.Month; import org.jfree.data.time.RegularTimePeriod; import org.jfree.data.time.Year;
public PeriodAxis(String label); public PeriodAxis(String label, RegularTimePeriod first, RegularTimePeriod last); public PeriodAxis(String label, RegularTimePeriod first, RegularTimePeriod last, TimeZone timeZone, Locale locale); public RegularTimePeriod getFirst(); public void setFirst(RegularTimePeriod first); public RegularTimePeriod getLast(); public void setLast(RegularTimePeriod last); public TimeZone getTimeZone(); public void setTimeZone(TimeZone zone); public Locale getLocale(); public Class getAutoRangeTimePeriodClass(); public void setAutoRangeTimePeriodClass(Class c); public Class getMajorTickTimePeriodClass(); public void setMajorTickTimePeriodClass(Class c); public boolean isMinorTickMarksVisible(); public void setMinorTickMarksVisible(boolean visible); public Class getMinorTickTimePeriodClass(); public void setMinorTickTimePeriodClass(Class c); public Stroke getMinorTickMarkStroke(); public void setMinorTickMarkStroke(Stroke stroke); public Paint getMinorTickMarkPaint(); public void setMinorTickMarkPaint(Paint paint); public float getMinorTickMarkInsideLength(); public void setMinorTickMarkInsideLength(float length); public float getMinorTickMarkOutsideLength(); public void setMinorTickMarkOutsideLength(float length); public PeriodAxisLabelInfo[] getLabelInfo(); public void setLabelInfo(PeriodAxisLabelInfo[] info); public Range getRange(); public void setRange(Range range, boolean turnOffAutoRange, boolean notify); public void configure(); public AxisSpace reserveSpace(Graphics2D g2, Plot plot, Rectangle2D plotArea, RectangleEdge edge, AxisSpace space); public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState); protected void drawTickMarks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); protected void drawTickMarksHorizontal(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); protected void drawTickMarksVertical(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); protected AxisState drawTickLabels(int band, Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); public List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); public double valueToJava2D(double value, Rectangle2D area, RectangleEdge edge); public double java2DToValue(double java2DValue, Rectangle2D area, RectangleEdge edge); protected void autoAdjustRange(); public boolean equals(Object obj); public int hashCode(); public Object clone() throws CloneNotSupportedException; private RegularTimePeriod createInstance(Class periodClass, Date millisecond, TimeZone zone, Locale locale); private void writeObject(ObjectOutputStream stream) throws IOException; private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException;
196
testEqualsWithLocale
```java private transient Paint minorTickMarkPaint = Color.black; private PeriodAxisLabelInfo[] labelInfo; public PeriodAxis(String label); public PeriodAxis(String label, RegularTimePeriod first, RegularTimePeriod last); public PeriodAxis(String label, RegularTimePeriod first, RegularTimePeriod last, TimeZone timeZone, Locale locale); public RegularTimePeriod getFirst(); public void setFirst(RegularTimePeriod first); public RegularTimePeriod getLast(); public void setLast(RegularTimePeriod last); public TimeZone getTimeZone(); public void setTimeZone(TimeZone zone); public Locale getLocale(); public Class getAutoRangeTimePeriodClass(); public void setAutoRangeTimePeriodClass(Class c); public Class getMajorTickTimePeriodClass(); public void setMajorTickTimePeriodClass(Class c); public boolean isMinorTickMarksVisible(); public void setMinorTickMarksVisible(boolean visible); public Class getMinorTickTimePeriodClass(); public void setMinorTickTimePeriodClass(Class c); public Stroke getMinorTickMarkStroke(); public void setMinorTickMarkStroke(Stroke stroke); public Paint getMinorTickMarkPaint(); public void setMinorTickMarkPaint(Paint paint); public float getMinorTickMarkInsideLength(); public void setMinorTickMarkInsideLength(float length); public float getMinorTickMarkOutsideLength(); public void setMinorTickMarkOutsideLength(float length); public PeriodAxisLabelInfo[] getLabelInfo(); public void setLabelInfo(PeriodAxisLabelInfo[] info); public Range getRange(); public void setRange(Range range, boolean turnOffAutoRange, boolean notify); public void configure(); public AxisSpace reserveSpace(Graphics2D g2, Plot plot, Rectangle2D plotArea, RectangleEdge edge, AxisSpace space); public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState); protected void drawTickMarks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); protected void drawTickMarksHorizontal(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); protected void drawTickMarksVertical(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); protected AxisState drawTickLabels(int band, Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); public List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); public double valueToJava2D(double value, Rectangle2D area, RectangleEdge edge); public double java2DToValue(double java2DValue, Rectangle2D area, RectangleEdge edge); protected void autoAdjustRange(); public boolean equals(Object obj); public int hashCode(); public Object clone() throws CloneNotSupportedException; private RegularTimePeriod createInstance(Class periodClass, Date millisecond, TimeZone zone, Locale locale); private void writeObject(ObjectOutputStream stream) throws IOException; private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException; } // Abstract Java Test Class package org.jfree.chart.axis.junit; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Stroke; 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.GregorianCalendar; import java.util.Locale; import java.util.SimpleTimeZone; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.axis.PeriodAxis; import org.jfree.chart.axis.PeriodAxisLabelInfo; import org.jfree.chart.event.AxisChangeEvent; import org.jfree.chart.event.AxisChangeListener; import org.jfree.data.Range; import org.jfree.data.time.DateRange; import org.jfree.data.time.Day; import org.jfree.data.time.Minute; import org.jfree.data.time.Month; import org.jfree.data.time.Quarter; import org.jfree.data.time.Second; import org.jfree.data.time.Year; public class PeriodAxisTests extends TestCase implements AxisChangeListener { private AxisChangeEvent lastEvent; private static final double EPSILON = 0.0000000001; public void axisChanged(AxisChangeEvent event); public static Test suite(); public PeriodAxisTests(String name); public void testEquals(); public void testEqualsWithLocale(); public void testHashCode(); public void testCloning(); public void testSerialization(); public void test1932146(); public void test2490803(); } ``` You are a professional Java test case writer, please create a test case named `testEqualsWithLocale` for the `PeriodAxis` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Confirm that the equals() method can distinguish the locale field (which * is new in version 1.0.13). */
182
// private transient Paint minorTickMarkPaint = Color.black; // private PeriodAxisLabelInfo[] labelInfo; // // public PeriodAxis(String label); // public PeriodAxis(String label, // RegularTimePeriod first, RegularTimePeriod last); // public PeriodAxis(String label, RegularTimePeriod first, // RegularTimePeriod last, TimeZone timeZone, Locale locale); // public RegularTimePeriod getFirst(); // public void setFirst(RegularTimePeriod first); // public RegularTimePeriod getLast(); // public void setLast(RegularTimePeriod last); // public TimeZone getTimeZone(); // public void setTimeZone(TimeZone zone); // public Locale getLocale(); // public Class getAutoRangeTimePeriodClass(); // public void setAutoRangeTimePeriodClass(Class c); // public Class getMajorTickTimePeriodClass(); // public void setMajorTickTimePeriodClass(Class c); // public boolean isMinorTickMarksVisible(); // public void setMinorTickMarksVisible(boolean visible); // public Class getMinorTickTimePeriodClass(); // public void setMinorTickTimePeriodClass(Class c); // public Stroke getMinorTickMarkStroke(); // public void setMinorTickMarkStroke(Stroke stroke); // public Paint getMinorTickMarkPaint(); // public void setMinorTickMarkPaint(Paint paint); // public float getMinorTickMarkInsideLength(); // public void setMinorTickMarkInsideLength(float length); // public float getMinorTickMarkOutsideLength(); // public void setMinorTickMarkOutsideLength(float length); // public PeriodAxisLabelInfo[] getLabelInfo(); // public void setLabelInfo(PeriodAxisLabelInfo[] info); // public Range getRange(); // public void setRange(Range range, boolean turnOffAutoRange, // boolean notify); // public void configure(); // public AxisSpace reserveSpace(Graphics2D g2, Plot plot, // Rectangle2D plotArea, RectangleEdge edge, // AxisSpace space); // public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, // Rectangle2D dataArea, RectangleEdge edge, // PlotRenderingInfo plotState); // protected void drawTickMarks(Graphics2D g2, AxisState state, // Rectangle2D dataArea, // RectangleEdge edge); // protected void drawTickMarksHorizontal(Graphics2D g2, AxisState state, // Rectangle2D dataArea, // RectangleEdge edge); // protected void drawTickMarksVertical(Graphics2D g2, AxisState state, // Rectangle2D dataArea, // RectangleEdge edge); // protected AxisState drawTickLabels(int band, Graphics2D g2, AxisState state, // Rectangle2D dataArea, // RectangleEdge edge); // public List refreshTicks(Graphics2D g2, AxisState state, // Rectangle2D dataArea, RectangleEdge edge); // public double valueToJava2D(double value, Rectangle2D area, // RectangleEdge edge); // public double java2DToValue(double java2DValue, Rectangle2D area, // RectangleEdge edge); // protected void autoAdjustRange(); // public boolean equals(Object obj); // public int hashCode(); // public Object clone() throws CloneNotSupportedException; // private RegularTimePeriod createInstance(Class periodClass, // Date millisecond, TimeZone zone, Locale locale); // private void writeObject(ObjectOutputStream stream) throws IOException; // private void readObject(ObjectInputStream stream) // throws IOException, ClassNotFoundException; // } // // // Abstract Java Test Class // package org.jfree.chart.axis.junit; // // import java.awt.BasicStroke; // import java.awt.Color; // import java.awt.Stroke; // 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.GregorianCalendar; // import java.util.Locale; // import java.util.SimpleTimeZone; // import java.util.TimeZone; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.chart.axis.PeriodAxis; // import org.jfree.chart.axis.PeriodAxisLabelInfo; // import org.jfree.chart.event.AxisChangeEvent; // import org.jfree.chart.event.AxisChangeListener; // import org.jfree.data.Range; // import org.jfree.data.time.DateRange; // import org.jfree.data.time.Day; // import org.jfree.data.time.Minute; // import org.jfree.data.time.Month; // import org.jfree.data.time.Quarter; // import org.jfree.data.time.Second; // import org.jfree.data.time.Year; // // // // public class PeriodAxisTests extends TestCase implements AxisChangeListener { // private AxisChangeEvent lastEvent; // private static final double EPSILON = 0.0000000001; // // public void axisChanged(AxisChangeEvent event); // public static Test suite(); // public PeriodAxisTests(String name); // public void testEquals(); // public void testEqualsWithLocale(); // public void testHashCode(); // public void testCloning(); // public void testSerialization(); // public void test1932146(); // public void test2490803(); // } // You are a professional Java test case writer, please create a test case named `testEqualsWithLocale` for the `PeriodAxis` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Confirm that the equals() method can distinguish the locale field (which * is new in version 1.0.13). */ public void testEqualsWithLocale() {
/** * Confirm that the equals() method can distinguish the locale field (which * is new in version 1.0.13). */
1
org.jfree.chart.axis.PeriodAxis
tests
```java private transient Paint minorTickMarkPaint = Color.black; private PeriodAxisLabelInfo[] labelInfo; public PeriodAxis(String label); public PeriodAxis(String label, RegularTimePeriod first, RegularTimePeriod last); public PeriodAxis(String label, RegularTimePeriod first, RegularTimePeriod last, TimeZone timeZone, Locale locale); public RegularTimePeriod getFirst(); public void setFirst(RegularTimePeriod first); public RegularTimePeriod getLast(); public void setLast(RegularTimePeriod last); public TimeZone getTimeZone(); public void setTimeZone(TimeZone zone); public Locale getLocale(); public Class getAutoRangeTimePeriodClass(); public void setAutoRangeTimePeriodClass(Class c); public Class getMajorTickTimePeriodClass(); public void setMajorTickTimePeriodClass(Class c); public boolean isMinorTickMarksVisible(); public void setMinorTickMarksVisible(boolean visible); public Class getMinorTickTimePeriodClass(); public void setMinorTickTimePeriodClass(Class c); public Stroke getMinorTickMarkStroke(); public void setMinorTickMarkStroke(Stroke stroke); public Paint getMinorTickMarkPaint(); public void setMinorTickMarkPaint(Paint paint); public float getMinorTickMarkInsideLength(); public void setMinorTickMarkInsideLength(float length); public float getMinorTickMarkOutsideLength(); public void setMinorTickMarkOutsideLength(float length); public PeriodAxisLabelInfo[] getLabelInfo(); public void setLabelInfo(PeriodAxisLabelInfo[] info); public Range getRange(); public void setRange(Range range, boolean turnOffAutoRange, boolean notify); public void configure(); public AxisSpace reserveSpace(Graphics2D g2, Plot plot, Rectangle2D plotArea, RectangleEdge edge, AxisSpace space); public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState); protected void drawTickMarks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); protected void drawTickMarksHorizontal(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); protected void drawTickMarksVertical(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); protected AxisState drawTickLabels(int band, Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); public List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); public double valueToJava2D(double value, Rectangle2D area, RectangleEdge edge); public double java2DToValue(double java2DValue, Rectangle2D area, RectangleEdge edge); protected void autoAdjustRange(); public boolean equals(Object obj); public int hashCode(); public Object clone() throws CloneNotSupportedException; private RegularTimePeriod createInstance(Class periodClass, Date millisecond, TimeZone zone, Locale locale); private void writeObject(ObjectOutputStream stream) throws IOException; private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException; } // Abstract Java Test Class package org.jfree.chart.axis.junit; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Stroke; 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.GregorianCalendar; import java.util.Locale; import java.util.SimpleTimeZone; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.axis.PeriodAxis; import org.jfree.chart.axis.PeriodAxisLabelInfo; import org.jfree.chart.event.AxisChangeEvent; import org.jfree.chart.event.AxisChangeListener; import org.jfree.data.Range; import org.jfree.data.time.DateRange; import org.jfree.data.time.Day; import org.jfree.data.time.Minute; import org.jfree.data.time.Month; import org.jfree.data.time.Quarter; import org.jfree.data.time.Second; import org.jfree.data.time.Year; public class PeriodAxisTests extends TestCase implements AxisChangeListener { private AxisChangeEvent lastEvent; private static final double EPSILON = 0.0000000001; public void axisChanged(AxisChangeEvent event); public static Test suite(); public PeriodAxisTests(String name); public void testEquals(); public void testEqualsWithLocale(); public void testHashCode(); public void testCloning(); public void testSerialization(); public void test1932146(); public void test2490803(); } ``` You are a professional Java test case writer, please create a test case named `testEqualsWithLocale` for the `PeriodAxis` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Confirm that the equals() method can distinguish the locale field (which * is new in version 1.0.13). */ public void testEqualsWithLocale() { ```
public class PeriodAxis extends ValueAxis implements Cloneable, PublicCloneable, Serializable
package org.jfree.chart.axis.junit; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Stroke; 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.GregorianCalendar; import java.util.Locale; import java.util.SimpleTimeZone; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.axis.PeriodAxis; import org.jfree.chart.axis.PeriodAxisLabelInfo; import org.jfree.chart.event.AxisChangeEvent; import org.jfree.chart.event.AxisChangeListener; import org.jfree.data.Range; import org.jfree.data.time.DateRange; import org.jfree.data.time.Day; import org.jfree.data.time.Minute; import org.jfree.data.time.Month; import org.jfree.data.time.Quarter; import org.jfree.data.time.Second; import org.jfree.data.time.Year;
public void axisChanged(AxisChangeEvent event); public static Test suite(); public PeriodAxisTests(String name); public void testEquals(); public void testEqualsWithLocale(); public void testHashCode(); public void testCloning(); public void testSerialization(); public void test1932146(); public void test2490803();
2c126ecaf8dabcc6e3a68f65218eb7f6ac2a6fdff68518c2923d09addfe6458d
[ "org.jfree.chart.axis.junit.PeriodAxisTests::testEqualsWithLocale" ]
private static final long serialVersionUID = 8353295532075872069L; private RegularTimePeriod first; private RegularTimePeriod last; private TimeZone timeZone; private Locale locale; private Calendar calendar; private Class autoRangeTimePeriodClass; private Class majorTickTimePeriodClass; private boolean minorTickMarksVisible; private Class minorTickTimePeriodClass; private float minorTickMarkInsideLength = 0.0f; private float minorTickMarkOutsideLength = 2.0f; private transient Stroke minorTickMarkStroke = new BasicStroke(0.5f); private transient Paint minorTickMarkPaint = Color.black; private PeriodAxisLabelInfo[] labelInfo;
public void testEqualsWithLocale()
private AxisChangeEvent lastEvent; 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.] * * -------------------- * PeriodAxisTests.java * -------------------- * (C) Copyright 2004-2009, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 10-Jun-2003 : Version 1 (DG); * 07-Jan-2005 : Added test for hashCode() method (DG); * 08-Apr-2008 : Added test1932146() (DG); * 16-Jan-2009 : Added test2490803() (DG); * 02-Mar-2009 : Added testEqualsWithLocale (DG); * */ package org.jfree.chart.axis.junit; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Stroke; 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.GregorianCalendar; import java.util.Locale; import java.util.SimpleTimeZone; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.axis.PeriodAxis; import org.jfree.chart.axis.PeriodAxisLabelInfo; import org.jfree.chart.event.AxisChangeEvent; import org.jfree.chart.event.AxisChangeListener; import org.jfree.data.Range; import org.jfree.data.time.DateRange; import org.jfree.data.time.Day; import org.jfree.data.time.Minute; import org.jfree.data.time.Month; import org.jfree.data.time.Quarter; import org.jfree.data.time.Second; import org.jfree.data.time.Year; /** * Tests for the {@link PeriodAxis} class. */ public class PeriodAxisTests extends TestCase implements AxisChangeListener { /** The last event received. */ private AxisChangeEvent lastEvent; /** * Receives and records an {@link AxisChangeEvent}. * * @param event the event. */ public void axisChanged(AxisChangeEvent event) { this.lastEvent = event; } /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(PeriodAxisTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public PeriodAxisTests(String name) { super(name); } /** * Confirm that the equals() method can distinguish all the required fields. */ public void testEquals() { PeriodAxis a1 = new PeriodAxis("Test"); PeriodAxis a2 = new PeriodAxis("Test"); assertTrue(a1.equals(a2)); assertTrue(a2.equals(a1)); a1.setFirst(new Year(2000)); assertFalse(a1.equals(a2)); a2.setFirst(new Year(2000)); assertTrue(a1.equals(a2)); a1.setLast(new Year(2004)); assertFalse(a1.equals(a2)); a2.setLast(new Year(2004)); assertTrue(a1.equals(a2)); a1.setTimeZone(TimeZone.getTimeZone("Pacific/Auckland")); assertFalse(a1.equals(a2)); a2.setTimeZone(TimeZone.getTimeZone("Pacific/Auckland")); assertTrue(a1.equals(a2)); a1.setAutoRangeTimePeriodClass(Quarter.class); assertFalse(a1.equals(a2)); a2.setAutoRangeTimePeriodClass(Quarter.class); assertTrue(a1.equals(a2)); PeriodAxisLabelInfo info[] = new PeriodAxisLabelInfo[1]; info[0] = new PeriodAxisLabelInfo(Month.class, new SimpleDateFormat("MMM")); a1.setLabelInfo(info); assertFalse(a1.equals(a2)); a2.setLabelInfo(info); assertTrue(a1.equals(a2)); a1.setMajorTickTimePeriodClass(Minute.class); assertFalse(a1.equals(a2)); a2.setMajorTickTimePeriodClass(Minute.class); assertTrue(a1.equals(a2)); a1.setMinorTickMarksVisible(!a1.isMinorTickMarksVisible()); assertFalse(a1.equals(a2)); a2.setMinorTickMarksVisible(a1.isMinorTickMarksVisible()); assertTrue(a1.equals(a2)); a1.setMinorTickTimePeriodClass(Minute.class); assertFalse(a1.equals(a2)); a2.setMinorTickTimePeriodClass(Minute.class); assertTrue(a1.equals(a2)); Stroke s = new BasicStroke(1.23f); a1.setMinorTickMarkStroke(s); assertFalse(a1.equals(a2)); a2.setMinorTickMarkStroke(s); assertTrue(a1.equals(a2)); a1.setMinorTickMarkPaint(Color.blue); assertFalse(a1.equals(a2)); a2.setMinorTickMarkPaint(Color.blue); assertTrue(a1.equals(a2)); } /** * Confirm that the equals() method can distinguish the locale field (which * is new in version 1.0.13). */ public void testEqualsWithLocale() { PeriodAxis a1 = new PeriodAxis("Test", new Year(2000), new Year(2009), TimeZone.getDefault(), Locale.JAPAN); PeriodAxis a2 = new PeriodAxis("Test", new Year(2000), new Year(2009), TimeZone.getDefault(), Locale.JAPAN); assertTrue(a1.equals(a2)); assertTrue(a2.equals(a1)); a1 = new PeriodAxis("Test", new Year(2000), new Year(2009), TimeZone.getDefault(), Locale.UK); assertFalse(a1.equals(a2)); a2 = new PeriodAxis("Test", new Year(2000), new Year(2009), TimeZone.getDefault(), Locale.UK); assertTrue(a1.equals(a2)); } /** * Two objects that are equal are required to return the same hashCode. */ public void testHashCode() { PeriodAxis a1 = new PeriodAxis("Test"); PeriodAxis a2 = new PeriodAxis("Test"); assertTrue(a1.equals(a2)); int h1 = a1.hashCode(); int h2 = a2.hashCode(); assertEquals(h1, h2); } /** * Confirm that cloning works. */ public void testCloning() { PeriodAxis a1 = new PeriodAxis("Test"); PeriodAxis a2 = null; try { a2 = (PeriodAxis) a1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(a1 != a2); assertTrue(a1.getClass() == a2.getClass()); assertTrue(a1.equals(a2)); // some checks that the clone is independent of the original a1.setLabel("New Label"); assertFalse(a1.equals(a2)); a2.setLabel("New Label"); assertTrue(a1.equals(a2)); a1.setFirst(new Year(1920)); assertFalse(a1.equals(a2)); a2.setFirst(new Year(1920)); assertTrue(a1.equals(a2)); a1.setLast(new Year(2020)); assertFalse(a1.equals(a2)); a2.setLast(new Year(2020)); assertTrue(a1.equals(a2)); PeriodAxisLabelInfo[] info = new PeriodAxisLabelInfo[2]; info[0] = new PeriodAxisLabelInfo(Day.class, new SimpleDateFormat("d")); info[1] = new PeriodAxisLabelInfo(Year.class, new SimpleDateFormat("yyyy")); a1.setLabelInfo(info); assertFalse(a1.equals(a2)); a2.setLabelInfo(info); assertTrue(a1.equals(a2)); a1.setAutoRangeTimePeriodClass(Second.class); assertFalse(a1.equals(a2)); a2.setAutoRangeTimePeriodClass(Second.class); assertTrue(a1.equals(a2)); a1.setTimeZone(new SimpleTimeZone(123, "Bogus")); assertFalse(a1.equals(a2)); a2.setTimeZone(new SimpleTimeZone(123, "Bogus")); assertTrue(a1.equals(a2)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { PeriodAxis a1 = new PeriodAxis("Test Axis"); PeriodAxis 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 = (PeriodAxis) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } boolean b = a1.equals(a2); assertTrue(b); } /** * A test for bug 1932146. */ public void test1932146() { PeriodAxis axis = new PeriodAxis("TestAxis"); axis.addChangeListener(this); this.lastEvent = null; axis.setRange(new DateRange(0L, 1000L)); assertTrue(this.lastEvent != null); } private static final double EPSILON = 0.0000000001; /** * A test for the setRange() method (because the axis shows whole time * periods, the range set for the axis will most likely be wider than the * one specified). */ public void test2490803() {} // Defects4J: flaky method // public void test2490803() { // Locale savedLocale = Locale.getDefault(); // TimeZone savedTimeZone = TimeZone.getDefault(); // try { // Locale.setDefault(Locale.FRANCE); // TimeZone.setDefault(TimeZone.getTimeZone("Europe/Paris")); // GregorianCalendar c0 = new GregorianCalendar(); // c0.clear(); // /* c0.set(2009, Calendar.JANUARY, 16, 12, 34, 56); // System.out.println(c0.getTime().getTime()); // c0.clear(); // c0.set(2009, Calendar.JANUARY, 17, 12, 34, 56); // System.out.println(c0.getTime().getTime()); */ // PeriodAxis axis = new PeriodAxis("TestAxis"); // axis.setRange(new Range(1232105696000L, 1232192096000L), false, // false); // Range r = axis.getRange(); // Day d0 = new Day(16, 1, 2009); // Day d1 = new Day(17, 1, 2009); // assertEquals(d0.getFirstMillisecond(), r.getLowerBound(), EPSILON); // assertEquals(d1.getLastMillisecond() + 1.0, r.getUpperBound(), // EPSILON); // } // finally { // TimeZone.setDefault(savedTimeZone); // Locale.setDefault(savedLocale); // } // } }
[ { "be_test_class_file": "org/jfree/chart/axis/PeriodAxis.java", "be_test_class_name": "org.jfree.chart.axis.PeriodAxis", "be_test_function_name": "class$", "be_test_function_signature": "(Ljava/lang/String;)Ljava/lang/Class;", "line_numbers": [ "239" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/PeriodAxis.java", "be_test_class_name": "org.jfree.chart.axis.PeriodAxis", "be_test_function_name": "equals", "be_test_function_signature": "(Ljava/lang/Object;)Z", "line_numbers": [ "1091", "1092", "1094", "1095", "1097", "1098", "1099", "1101", "1102", "1104", "1105", "1107", "1108", "1110", "1112", "1114", "1116", "1118", "1120", "1122", "1124", "1126", "1127", "1129", "1130", "1132", "1133", "1135" ], "method_line_rate": 0.5714285714285714 }, { "be_test_class_file": "org/jfree/chart/axis/PeriodAxis.java", "be_test_class_name": "org.jfree.chart.axis.PeriodAxis", "be_test_function_name": "isMinorTickMarksVisible", "be_test_function_signature": "()Z", "line_numbers": [ "387" ], "method_line_rate": 1 } ]
public final class PolynomialFunctionTest
@Test public void testMath341() { double[] f_coeff = { 3, 6, -2, 1 }; double[] g_coeff = { 6, -4, 3 }; double[] h_coeff = { -4, 6 }; PolynomialFunction f = new PolynomialFunction(f_coeff); PolynomialFunction g = new PolynomialFunction(g_coeff); PolynomialFunction h = new PolynomialFunction(h_coeff); // compare f' = g Assert.assertEquals(f.derivative().value(0), g.value(0), tolerance); Assert.assertEquals(f.derivative().value(1), g.value(1), tolerance); Assert.assertEquals(f.derivative().value(100), g.value(100), tolerance); Assert.assertEquals(f.derivative().value(4.1), g.value(4.1), tolerance); Assert.assertEquals(f.derivative().value(-3.25), g.value(-3.25), tolerance); // compare g' = h Assert.assertEquals(g.derivative().value(FastMath.PI), h.value(FastMath.PI), tolerance); Assert.assertEquals(g.derivative().value(FastMath.E), h.value(FastMath.E), tolerance); }
// // Abstract Java Tested Class // package org.apache.commons.math3.analysis.polynomials; // // import java.io.Serializable; // import java.util.Arrays; // import org.apache.commons.math3.exception.util.LocalizedFormats; // import org.apache.commons.math3.exception.NoDataException; // import org.apache.commons.math3.exception.NullArgumentException; // import org.apache.commons.math3.analysis.DifferentiableUnivariateFunction; // import org.apache.commons.math3.analysis.UnivariateFunction; // import org.apache.commons.math3.analysis.ParametricUnivariateFunction; // import org.apache.commons.math3.analysis.differentiation.DerivativeStructure; // import org.apache.commons.math3.analysis.differentiation.UnivariateDifferentiableFunction; // import org.apache.commons.math3.util.FastMath; // import org.apache.commons.math3.util.MathUtils; // // // // public class PolynomialFunction implements UnivariateDifferentiableFunction, DifferentiableUnivariateFunction, Serializable { // private static final long serialVersionUID = -7726511984200295583L; // private final double coefficients[]; // // public PolynomialFunction(double c[]) // throws NullArgumentException, NoDataException; // public double value(double x); // public int degree(); // public double[] getCoefficients(); // protected static double evaluate(double[] coefficients, double argument) // throws NullArgumentException, NoDataException; // public DerivativeStructure value(final DerivativeStructure t) // throws NullArgumentException, NoDataException; // public PolynomialFunction add(final PolynomialFunction p); // public PolynomialFunction subtract(final PolynomialFunction p); // public PolynomialFunction negate(); // public PolynomialFunction multiply(final PolynomialFunction p); // protected static double[] differentiate(double[] coefficients) // throws NullArgumentException, NoDataException; // public PolynomialFunction polynomialDerivative(); // public UnivariateFunction derivative(); // @Override // public String toString(); // private static String toString(double coeff); // @Override // public int hashCode(); // @Override // public boolean equals(Object obj); // public double[] gradient(double x, double ... parameters); // public double value(final double x, final double ... parameters) // throws NoDataException; // } // // // Abstract Java Test Class // package org.apache.commons.math3.analysis.polynomials; // // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.util.FastMath; // import org.junit.Test; // import org.junit.Assert; // // // // public final class PolynomialFunctionTest { // protected double tolerance = 1e-12; // // @Test // public void testConstants(); // @Test // public void testLinear(); // @Test // public void testQuadratic(); // @Test // public void testQuintic(); // @Test // public void testfirstDerivativeComparison(); // @Test // public void testString(); // @Test // public void testAddition(); // @Test // public void testSubtraction(); // @Test // public void testMultiplication(); // @Test // public void testSerial(); // @Test // public void testMath341(); // public void checkPolynomial(PolynomialFunction p, String reference); // private void checkNullPolynomial(PolynomialFunction p); // } // You are a professional Java test case writer, please create a test case named `testMath341` for the `PolynomialFunction` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * tests the firstDerivative function by comparison * * <p>This will test the functions * <tt>f(x) = x^3 - 2x^2 + 6x + 3, g(x) = 3x^2 - 4x + 6</tt> * and <tt>h(x) = 6x - 4</tt> */
src/test/java/org/apache/commons/math3/analysis/polynomials/PolynomialFunctionTest.java
package org.apache.commons.math3.analysis.polynomials; import java.io.Serializable; import java.util.Arrays; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.exception.NoDataException; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.analysis.DifferentiableUnivariateFunction; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.ParametricUnivariateFunction; import org.apache.commons.math3.analysis.differentiation.DerivativeStructure; import org.apache.commons.math3.analysis.differentiation.UnivariateDifferentiableFunction; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.MathUtils;
public PolynomialFunction(double c[]) throws NullArgumentException, NoDataException; public double value(double x); public int degree(); public double[] getCoefficients(); protected static double evaluate(double[] coefficients, double argument) throws NullArgumentException, NoDataException; public DerivativeStructure value(final DerivativeStructure t) throws NullArgumentException, NoDataException; public PolynomialFunction add(final PolynomialFunction p); public PolynomialFunction subtract(final PolynomialFunction p); public PolynomialFunction negate(); public PolynomialFunction multiply(final PolynomialFunction p); protected static double[] differentiate(double[] coefficients) throws NullArgumentException, NoDataException; public PolynomialFunction polynomialDerivative(); public UnivariateFunction derivative(); @Override public String toString(); private static String toString(double coeff); @Override public int hashCode(); @Override public boolean equals(Object obj); public double[] gradient(double x, double ... parameters); public double value(final double x, final double ... parameters) throws NoDataException;
253
testMath341
```java // Abstract Java Tested Class package org.apache.commons.math3.analysis.polynomials; import java.io.Serializable; import java.util.Arrays; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.exception.NoDataException; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.analysis.DifferentiableUnivariateFunction; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.ParametricUnivariateFunction; import org.apache.commons.math3.analysis.differentiation.DerivativeStructure; import org.apache.commons.math3.analysis.differentiation.UnivariateDifferentiableFunction; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.MathUtils; public class PolynomialFunction implements UnivariateDifferentiableFunction, DifferentiableUnivariateFunction, Serializable { private static final long serialVersionUID = -7726511984200295583L; private final double coefficients[]; public PolynomialFunction(double c[]) throws NullArgumentException, NoDataException; public double value(double x); public int degree(); public double[] getCoefficients(); protected static double evaluate(double[] coefficients, double argument) throws NullArgumentException, NoDataException; public DerivativeStructure value(final DerivativeStructure t) throws NullArgumentException, NoDataException; public PolynomialFunction add(final PolynomialFunction p); public PolynomialFunction subtract(final PolynomialFunction p); public PolynomialFunction negate(); public PolynomialFunction multiply(final PolynomialFunction p); protected static double[] differentiate(double[] coefficients) throws NullArgumentException, NoDataException; public PolynomialFunction polynomialDerivative(); public UnivariateFunction derivative(); @Override public String toString(); private static String toString(double coeff); @Override public int hashCode(); @Override public boolean equals(Object obj); public double[] gradient(double x, double ... parameters); public double value(final double x, final double ... parameters) throws NoDataException; } // Abstract Java Test Class package org.apache.commons.math3.analysis.polynomials; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert; public final class PolynomialFunctionTest { protected double tolerance = 1e-12; @Test public void testConstants(); @Test public void testLinear(); @Test public void testQuadratic(); @Test public void testQuintic(); @Test public void testfirstDerivativeComparison(); @Test public void testString(); @Test public void testAddition(); @Test public void testSubtraction(); @Test public void testMultiplication(); @Test public void testSerial(); @Test public void testMath341(); public void checkPolynomial(PolynomialFunction p, String reference); private void checkNullPolynomial(PolynomialFunction p); } ``` You are a professional Java test case writer, please create a test case named `testMath341` for the `PolynomialFunction` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * tests the firstDerivative function by comparison * * <p>This will test the functions * <tt>f(x) = x^3 - 2x^2 + 6x + 3, g(x) = 3x^2 - 4x + 6</tt> * and <tt>h(x) = 6x - 4</tt> */
233
// // Abstract Java Tested Class // package org.apache.commons.math3.analysis.polynomials; // // import java.io.Serializable; // import java.util.Arrays; // import org.apache.commons.math3.exception.util.LocalizedFormats; // import org.apache.commons.math3.exception.NoDataException; // import org.apache.commons.math3.exception.NullArgumentException; // import org.apache.commons.math3.analysis.DifferentiableUnivariateFunction; // import org.apache.commons.math3.analysis.UnivariateFunction; // import org.apache.commons.math3.analysis.ParametricUnivariateFunction; // import org.apache.commons.math3.analysis.differentiation.DerivativeStructure; // import org.apache.commons.math3.analysis.differentiation.UnivariateDifferentiableFunction; // import org.apache.commons.math3.util.FastMath; // import org.apache.commons.math3.util.MathUtils; // // // // public class PolynomialFunction implements UnivariateDifferentiableFunction, DifferentiableUnivariateFunction, Serializable { // private static final long serialVersionUID = -7726511984200295583L; // private final double coefficients[]; // // public PolynomialFunction(double c[]) // throws NullArgumentException, NoDataException; // public double value(double x); // public int degree(); // public double[] getCoefficients(); // protected static double evaluate(double[] coefficients, double argument) // throws NullArgumentException, NoDataException; // public DerivativeStructure value(final DerivativeStructure t) // throws NullArgumentException, NoDataException; // public PolynomialFunction add(final PolynomialFunction p); // public PolynomialFunction subtract(final PolynomialFunction p); // public PolynomialFunction negate(); // public PolynomialFunction multiply(final PolynomialFunction p); // protected static double[] differentiate(double[] coefficients) // throws NullArgumentException, NoDataException; // public PolynomialFunction polynomialDerivative(); // public UnivariateFunction derivative(); // @Override // public String toString(); // private static String toString(double coeff); // @Override // public int hashCode(); // @Override // public boolean equals(Object obj); // public double[] gradient(double x, double ... parameters); // public double value(final double x, final double ... parameters) // throws NoDataException; // } // // // Abstract Java Test Class // package org.apache.commons.math3.analysis.polynomials; // // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.util.FastMath; // import org.junit.Test; // import org.junit.Assert; // // // // public final class PolynomialFunctionTest { // protected double tolerance = 1e-12; // // @Test // public void testConstants(); // @Test // public void testLinear(); // @Test // public void testQuadratic(); // @Test // public void testQuintic(); // @Test // public void testfirstDerivativeComparison(); // @Test // public void testString(); // @Test // public void testAddition(); // @Test // public void testSubtraction(); // @Test // public void testMultiplication(); // @Test // public void testSerial(); // @Test // public void testMath341(); // public void checkPolynomial(PolynomialFunction p, String reference); // private void checkNullPolynomial(PolynomialFunction p); // } // You are a professional Java test case writer, please create a test case named `testMath341` for the `PolynomialFunction` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * tests the firstDerivative function by comparison * * <p>This will test the functions * <tt>f(x) = x^3 - 2x^2 + 6x + 3, g(x) = 3x^2 - 4x + 6</tt> * and <tt>h(x) = 6x - 4</tt> */ @Test public void testMath341() {
/** * tests the firstDerivative function by comparison * * <p>This will test the functions * <tt>f(x) = x^3 - 2x^2 + 6x + 3, g(x) = 3x^2 - 4x + 6</tt> * and <tt>h(x) = 6x - 4</tt> */
1
org.apache.commons.math3.analysis.polynomials.PolynomialFunction
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.math3.analysis.polynomials; import java.io.Serializable; import java.util.Arrays; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.exception.NoDataException; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.analysis.DifferentiableUnivariateFunction; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.ParametricUnivariateFunction; import org.apache.commons.math3.analysis.differentiation.DerivativeStructure; import org.apache.commons.math3.analysis.differentiation.UnivariateDifferentiableFunction; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.MathUtils; public class PolynomialFunction implements UnivariateDifferentiableFunction, DifferentiableUnivariateFunction, Serializable { private static final long serialVersionUID = -7726511984200295583L; private final double coefficients[]; public PolynomialFunction(double c[]) throws NullArgumentException, NoDataException; public double value(double x); public int degree(); public double[] getCoefficients(); protected static double evaluate(double[] coefficients, double argument) throws NullArgumentException, NoDataException; public DerivativeStructure value(final DerivativeStructure t) throws NullArgumentException, NoDataException; public PolynomialFunction add(final PolynomialFunction p); public PolynomialFunction subtract(final PolynomialFunction p); public PolynomialFunction negate(); public PolynomialFunction multiply(final PolynomialFunction p); protected static double[] differentiate(double[] coefficients) throws NullArgumentException, NoDataException; public PolynomialFunction polynomialDerivative(); public UnivariateFunction derivative(); @Override public String toString(); private static String toString(double coeff); @Override public int hashCode(); @Override public boolean equals(Object obj); public double[] gradient(double x, double ... parameters); public double value(final double x, final double ... parameters) throws NoDataException; } // Abstract Java Test Class package org.apache.commons.math3.analysis.polynomials; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert; public final class PolynomialFunctionTest { protected double tolerance = 1e-12; @Test public void testConstants(); @Test public void testLinear(); @Test public void testQuadratic(); @Test public void testQuintic(); @Test public void testfirstDerivativeComparison(); @Test public void testString(); @Test public void testAddition(); @Test public void testSubtraction(); @Test public void testMultiplication(); @Test public void testSerial(); @Test public void testMath341(); public void checkPolynomial(PolynomialFunction p, String reference); private void checkNullPolynomial(PolynomialFunction p); } ``` You are a professional Java test case writer, please create a test case named `testMath341` for the `PolynomialFunction` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * tests the firstDerivative function by comparison * * <p>This will test the functions * <tt>f(x) = x^3 - 2x^2 + 6x + 3, g(x) = 3x^2 - 4x + 6</tt> * and <tt>h(x) = 6x - 4</tt> */ @Test public void testMath341() { ```
public class PolynomialFunction implements UnivariateDifferentiableFunction, DifferentiableUnivariateFunction, Serializable
package org.apache.commons.math3.analysis.polynomials; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert;
@Test public void testConstants(); @Test public void testLinear(); @Test public void testQuadratic(); @Test public void testQuintic(); @Test public void testfirstDerivativeComparison(); @Test public void testString(); @Test public void testAddition(); @Test public void testSubtraction(); @Test public void testMultiplication(); @Test public void testSerial(); @Test public void testMath341(); public void checkPolynomial(PolynomialFunction p, String reference); private void checkNullPolynomial(PolynomialFunction p);
2d1e6580f3cb65ff9ca4cca98fda4c6e51a25228ef9c54cbc9e6a5b85e14ce56
[ "org.apache.commons.math3.analysis.polynomials.PolynomialFunctionTest::testMath341" ]
private static final long serialVersionUID = -7726511984200295583L; private final double coefficients[];
@Test public void testMath341()
protected double tolerance = 1e-12;
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.polynomials; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert; /** * Tests the PolynomialFunction implementation of a UnivariateFunction. * * @version $Id$ */ public final class PolynomialFunctionTest { /** Error tolerance for tests */ protected double tolerance = 1e-12; /** * tests the value of a constant polynomial. * * <p>value of this is 2.5 everywhere.</p> */ @Test public void testConstants() { double[] c = { 2.5 }; PolynomialFunction f = new PolynomialFunction(c); // verify that we are equal to c[0] at several (nonsymmetric) places Assert.assertEquals(f.value(0), c[0], tolerance); Assert.assertEquals(f.value(-1), c[0], tolerance); Assert.assertEquals(f.value(-123.5), c[0], tolerance); Assert.assertEquals(f.value(3), c[0], tolerance); Assert.assertEquals(f.value(456.89), c[0], tolerance); Assert.assertEquals(f.degree(), 0); Assert.assertEquals(f.derivative().value(0), 0, tolerance); Assert.assertEquals(f.polynomialDerivative().derivative().value(0), 0, tolerance); } /** * tests the value of a linear polynomial. * * <p>This will test the function f(x) = 3*x - 1.5</p> * <p>This will have the values * <tt>f(0) = -1.5, f(-1) = -4.5, f(-2.5) = -9, * f(0.5) = 0, f(1.5) = 3</tt> and <tt>f(3) = 7.5</tt> * </p> */ @Test public void testLinear() { double[] c = { -1.5, 3 }; PolynomialFunction f = new PolynomialFunction(c); // verify that we are equal to c[0] when x=0 Assert.assertEquals(f.value(0), c[0], tolerance); // now check a few other places Assert.assertEquals(-4.5, f.value(-1), tolerance); Assert.assertEquals(-9, f.value(-2.5), tolerance); Assert.assertEquals(0, f.value(0.5), tolerance); Assert.assertEquals(3, f.value(1.5), tolerance); Assert.assertEquals(7.5, f.value(3), tolerance); Assert.assertEquals(f.degree(), 1); Assert.assertEquals(f.polynomialDerivative().derivative().value(0), 0, tolerance); } /** * Tests a second order polynomial. * <p> This will test the function f(x) = 2x^2 - 3x -2 = (2x+1)(x-2)</p> */ @Test public void testQuadratic() { double[] c = { -2, -3, 2 }; PolynomialFunction f = new PolynomialFunction(c); // verify that we are equal to c[0] when x=0 Assert.assertEquals(f.value(0), c[0], tolerance); // now check a few other places Assert.assertEquals(0, f.value(-0.5), tolerance); Assert.assertEquals(0, f.value(2), tolerance); Assert.assertEquals(-2, f.value(1.5), tolerance); Assert.assertEquals(7, f.value(-1.5), tolerance); Assert.assertEquals(265.5312, f.value(12.34), tolerance); } /** * This will test the quintic function * f(x) = x^2(x-5)(x+3)(x-1) = x^5 - 3x^4 -13x^3 + 15x^2</p> */ @Test public void testQuintic() { double[] c = { 0, 0, 15, -13, -3, 1 }; PolynomialFunction f = new PolynomialFunction(c); // verify that we are equal to c[0] when x=0 Assert.assertEquals(f.value(0), c[0], tolerance); // now check a few other places Assert.assertEquals(0, f.value(5), tolerance); Assert.assertEquals(0, f.value(1), tolerance); Assert.assertEquals(0, f.value(-3), tolerance); Assert.assertEquals(54.84375, f.value(-1.5), tolerance); Assert.assertEquals(-8.06637, f.value(1.3), tolerance); Assert.assertEquals(f.degree(), 5); } /** * tests the firstDerivative function by comparison * * <p>This will test the functions * <tt>f(x) = x^3 - 2x^2 + 6x + 3, g(x) = 3x^2 - 4x + 6</tt> * and <tt>h(x) = 6x - 4</tt> */ @Test public void testfirstDerivativeComparison() { double[] f_coeff = { 3, 6, -2, 1 }; double[] g_coeff = { 6, -4, 3 }; double[] h_coeff = { -4, 6 }; PolynomialFunction f = new PolynomialFunction(f_coeff); PolynomialFunction g = new PolynomialFunction(g_coeff); PolynomialFunction h = new PolynomialFunction(h_coeff); // compare f' = g Assert.assertEquals(f.derivative().value(0), g.value(0), tolerance); Assert.assertEquals(f.derivative().value(1), g.value(1), tolerance); Assert.assertEquals(f.derivative().value(100), g.value(100), tolerance); Assert.assertEquals(f.derivative().value(4.1), g.value(4.1), tolerance); Assert.assertEquals(f.derivative().value(-3.25), g.value(-3.25), tolerance); // compare g' = h Assert.assertEquals(g.derivative().value(FastMath.PI), h.value(FastMath.PI), tolerance); Assert.assertEquals(g.derivative().value(FastMath.E), h.value(FastMath.E), tolerance); } @Test public void testString() { PolynomialFunction p = new PolynomialFunction(new double[] { -5, 3, 1 }); checkPolynomial(p, "-5 + 3 x + x^2"); checkPolynomial(new PolynomialFunction(new double[] { 0, -2, 3 }), "-2 x + 3 x^2"); checkPolynomial(new PolynomialFunction(new double[] { 1, -2, 3 }), "1 - 2 x + 3 x^2"); checkPolynomial(new PolynomialFunction(new double[] { 0, 2, 3 }), "2 x + 3 x^2"); checkPolynomial(new PolynomialFunction(new double[] { 1, 2, 3 }), "1 + 2 x + 3 x^2"); checkPolynomial(new PolynomialFunction(new double[] { 1, 0, 3 }), "1 + 3 x^2"); checkPolynomial(new PolynomialFunction(new double[] { 0 }), "0"); } @Test public void testAddition() { PolynomialFunction p1 = new PolynomialFunction(new double[] { -2, 1 }); PolynomialFunction p2 = new PolynomialFunction(new double[] { 2, -1, 0 }); checkNullPolynomial(p1.add(p2)); p2 = p1.add(p1); checkPolynomial(p2, "-4 + 2 x"); p1 = new PolynomialFunction(new double[] { 1, -4, 2 }); p2 = new PolynomialFunction(new double[] { -1, 3, -2 }); p1 = p1.add(p2); Assert.assertEquals(1, p1.degree()); checkPolynomial(p1, "-x"); } @Test public void testSubtraction() { PolynomialFunction p1 = new PolynomialFunction(new double[] { -2, 1 }); checkNullPolynomial(p1.subtract(p1)); PolynomialFunction p2 = new PolynomialFunction(new double[] { -2, 6 }); p2 = p2.subtract(p1); checkPolynomial(p2, "5 x"); p1 = new PolynomialFunction(new double[] { 1, -4, 2 }); p2 = new PolynomialFunction(new double[] { -1, 3, 2 }); p1 = p1.subtract(p2); Assert.assertEquals(1, p1.degree()); checkPolynomial(p1, "2 - 7 x"); } @Test public void testMultiplication() { PolynomialFunction p1 = new PolynomialFunction(new double[] { -3, 2 }); PolynomialFunction p2 = new PolynomialFunction(new double[] { 3, 2, 1 }); checkPolynomial(p1.multiply(p2), "-9 + x^2 + 2 x^3"); p1 = new PolynomialFunction(new double[] { 0, 1 }); p2 = p1; for (int i = 2; i < 10; ++i) { p2 = p2.multiply(p1); checkPolynomial(p2, "x^" + i); } } @Test public void testSerial() { PolynomialFunction p2 = new PolynomialFunction(new double[] { 3, 2, 1 }); Assert.assertEquals(p2, TestUtils.serializeAndRecover(p2)); } /** * tests the firstDerivative function by comparison * * <p>This will test the functions * <tt>f(x) = x^3 - 2x^2 + 6x + 3, g(x) = 3x^2 - 4x + 6</tt> * and <tt>h(x) = 6x - 4</tt> */ @Test public void testMath341() { double[] f_coeff = { 3, 6, -2, 1 }; double[] g_coeff = { 6, -4, 3 }; double[] h_coeff = { -4, 6 }; PolynomialFunction f = new PolynomialFunction(f_coeff); PolynomialFunction g = new PolynomialFunction(g_coeff); PolynomialFunction h = new PolynomialFunction(h_coeff); // compare f' = g Assert.assertEquals(f.derivative().value(0), g.value(0), tolerance); Assert.assertEquals(f.derivative().value(1), g.value(1), tolerance); Assert.assertEquals(f.derivative().value(100), g.value(100), tolerance); Assert.assertEquals(f.derivative().value(4.1), g.value(4.1), tolerance); Assert.assertEquals(f.derivative().value(-3.25), g.value(-3.25), tolerance); // compare g' = h Assert.assertEquals(g.derivative().value(FastMath.PI), h.value(FastMath.PI), tolerance); Assert.assertEquals(g.derivative().value(FastMath.E), h.value(FastMath.E), tolerance); } public void checkPolynomial(PolynomialFunction p, String reference) { Assert.assertEquals(reference, p.toString()); } private void checkNullPolynomial(PolynomialFunction p) { for (double coefficient : p.getCoefficients()) { Assert.assertEquals(0, coefficient, 1e-15); } } }
[ { "be_test_class_file": "org/apache/commons/math3/analysis/polynomials/PolynomialFunction.java", "be_test_class_name": "org.apache.commons.math3.analysis.polynomials.PolynomialFunction", "be_test_function_name": "derivative", "be_test_function_signature": "()Lorg/apache/commons/math3/analysis/UnivariateFunction;", "line_numbers": [ "290" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/analysis/polynomials/PolynomialFunction.java", "be_test_class_name": "org.apache.commons.math3.analysis.polynomials.PolynomialFunction", "be_test_function_name": "differentiate", "be_test_function_signature": "([D)[D", "line_numbers": [ "260", "261", "262", "263", "265", "266", "268", "269", "270", "272" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/apache/commons/math3/analysis/polynomials/PolynomialFunction.java", "be_test_class_name": "org.apache.commons.math3.analysis.polynomials.PolynomialFunction", "be_test_function_name": "evaluate", "be_test_function_signature": "([DD)D", "line_numbers": [ "130", "131", "132", "133", "135", "136", "137", "139" ], "method_line_rate": 0.875 }, { "be_test_class_file": "org/apache/commons/math3/analysis/polynomials/PolynomialFunction.java", "be_test_class_name": "org.apache.commons.math3.analysis.polynomials.PolynomialFunction", "be_test_function_name": "polynomialDerivative", "be_test_function_signature": "()Lorg/apache/commons/math3/analysis/polynomials/PolynomialFunction;", "line_numbers": [ "281" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/analysis/polynomials/PolynomialFunction.java", "be_test_class_name": "org.apache.commons.math3.analysis.polynomials.PolynomialFunction", "be_test_function_name": "value", "be_test_function_signature": "(D)D", "line_numbers": [ "94" ], "method_line_rate": 1 } ]
public final class BrentOptimizerTest
@Test public void testKeepInitIfBest() { final double minSin = 3 * Math.PI / 2; final double offset = 1e-8; final double delta = 1e-7; final UnivariateFunction f1 = new Sin(); final UnivariateFunction f2 = new StepFunction(new double[] { minSin, minSin + offset, minSin + 2 * offset}, new double[] { 0, -1, 0 }); final UnivariateFunction f = FunctionUtils.add(f1, f2); // A slightly less stringent tolerance would make the test pass // even with the previous implementation. final double relTol = 1e-8; final UnivariateOptimizer optimizer = new BrentOptimizer(relTol, 1e-100); final double init = minSin + 1.5 * offset; final UnivariatePointValuePair result = optimizer.optimize(200, f, GoalType.MINIMIZE, minSin - 6.789 * delta, minSin + 9.876 * delta, init); final int numEval = optimizer.getEvaluations(); final double sol = result.getPoint(); final double expected = init; // System.out.println("numEval=" + numEval); // System.out.println("min=" + init + " f=" + f.value(init)); // System.out.println("sol=" + sol + " f=" + f.value(sol)); // System.out.println("exp=" + expected + " f=" + f.value(expected)); Assert.assertTrue("Best point not reported", f.value(sol) <= f.value(expected)); }
// // Abstract Java Tested Class // package org.apache.commons.math3.optimization.univariate; // // import org.apache.commons.math3.util.Precision; // import org.apache.commons.math3.util.FastMath; // import org.apache.commons.math3.exception.NumberIsTooSmallException; // import org.apache.commons.math3.exception.NotStrictlyPositiveException; // import org.apache.commons.math3.optimization.ConvergenceChecker; // import org.apache.commons.math3.optimization.GoalType; // // // // @Deprecated // public class BrentOptimizer extends BaseAbstractUnivariateOptimizer { // private static final double GOLDEN_SECTION = 0.5 * (3 - FastMath.sqrt(5)); // private static final double MIN_RELATIVE_TOLERANCE = 2 * FastMath.ulp(1d); // private final double relativeThreshold; // private final double absoluteThreshold; // // public BrentOptimizer(double rel, // double abs, // ConvergenceChecker<UnivariatePointValuePair> checker); // public BrentOptimizer(double rel, // double abs); // @Override // protected UnivariatePointValuePair doOptimize(); // private UnivariatePointValuePair best(UnivariatePointValuePair a, // UnivariatePointValuePair b, // boolean isMinim); // } // // // Abstract Java Test Class // package org.apache.commons.math3.optimization.univariate; // // import org.apache.commons.math3.analysis.QuinticFunction; // import org.apache.commons.math3.analysis.UnivariateFunction; // import org.apache.commons.math3.analysis.function.Sin; // import org.apache.commons.math3.analysis.function.StepFunction; // import org.apache.commons.math3.analysis.FunctionUtils; // import org.apache.commons.math3.exception.NumberIsTooLargeException; // import org.apache.commons.math3.exception.NumberIsTooSmallException; // import org.apache.commons.math3.exception.TooManyEvaluationsException; // import org.apache.commons.math3.optimization.ConvergenceChecker; // import org.apache.commons.math3.optimization.GoalType; // import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; // import org.apache.commons.math3.util.FastMath; // import org.junit.Assert; // import org.junit.Test; // // // // public final class BrentOptimizerTest { // // // @Test // public void testSinMin(); // @Test // public void testSinMinWithValueChecker(); // @Test // public void testBoundaries(); // @Test // public void testQuinticMin(); // @Test // public void testQuinticMinStatistics(); // @Test // public void testQuinticMax(); // @Test // public void testMinEndpoints(); // @Test // public void testMath832(); // @Test // public void testKeepInitIfBest(); // @Test // public void testMath855(); // public double value(double x); // public double value(double x); // } // You are a professional Java test case writer, please create a test case named `testKeepInitIfBest` for the `BrentOptimizer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Contrived example showing that prior to the resolution of MATH-855 * (second revision), the algorithm would not return the best point if * it happened to be the initial guess. */
src/test/java/org/apache/commons/math3/optimization/univariate/BrentOptimizerTest.java
package org.apache.commons.math3.optimization.univariate; import org.apache.commons.math3.util.Precision; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.optimization.ConvergenceChecker; import org.apache.commons.math3.optimization.GoalType;
public BrentOptimizer(double rel, double abs, ConvergenceChecker<UnivariatePointValuePair> checker); public BrentOptimizer(double rel, double abs); @Override protected UnivariatePointValuePair doOptimize(); private UnivariatePointValuePair best(UnivariatePointValuePair a, UnivariatePointValuePair b, boolean isMinim);
221
testKeepInitIfBest
```java // Abstract Java Tested Class package org.apache.commons.math3.optimization.univariate; import org.apache.commons.math3.util.Precision; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.optimization.ConvergenceChecker; import org.apache.commons.math3.optimization.GoalType; @Deprecated public class BrentOptimizer extends BaseAbstractUnivariateOptimizer { private static final double GOLDEN_SECTION = 0.5 * (3 - FastMath.sqrt(5)); private static final double MIN_RELATIVE_TOLERANCE = 2 * FastMath.ulp(1d); private final double relativeThreshold; private final double absoluteThreshold; public BrentOptimizer(double rel, double abs, ConvergenceChecker<UnivariatePointValuePair> checker); public BrentOptimizer(double rel, double abs); @Override protected UnivariatePointValuePair doOptimize(); private UnivariatePointValuePair best(UnivariatePointValuePair a, UnivariatePointValuePair b, boolean isMinim); } // Abstract Java Test Class package org.apache.commons.math3.optimization.univariate; import org.apache.commons.math3.analysis.QuinticFunction; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.function.Sin; import org.apache.commons.math3.analysis.function.StepFunction; import org.apache.commons.math3.analysis.FunctionUtils; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.exception.TooManyEvaluationsException; import org.apache.commons.math3.optimization.ConvergenceChecker; import org.apache.commons.math3.optimization.GoalType; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; public final class BrentOptimizerTest { @Test public void testSinMin(); @Test public void testSinMinWithValueChecker(); @Test public void testBoundaries(); @Test public void testQuinticMin(); @Test public void testQuinticMinStatistics(); @Test public void testQuinticMax(); @Test public void testMinEndpoints(); @Test public void testMath832(); @Test public void testKeepInitIfBest(); @Test public void testMath855(); public double value(double x); public double value(double x); } ``` You are a professional Java test case writer, please create a test case named `testKeepInitIfBest` for the `BrentOptimizer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Contrived example showing that prior to the resolution of MATH-855 * (second revision), the algorithm would not return the best point if * it happened to be the initial guess. */
191
// // Abstract Java Tested Class // package org.apache.commons.math3.optimization.univariate; // // import org.apache.commons.math3.util.Precision; // import org.apache.commons.math3.util.FastMath; // import org.apache.commons.math3.exception.NumberIsTooSmallException; // import org.apache.commons.math3.exception.NotStrictlyPositiveException; // import org.apache.commons.math3.optimization.ConvergenceChecker; // import org.apache.commons.math3.optimization.GoalType; // // // // @Deprecated // public class BrentOptimizer extends BaseAbstractUnivariateOptimizer { // private static final double GOLDEN_SECTION = 0.5 * (3 - FastMath.sqrt(5)); // private static final double MIN_RELATIVE_TOLERANCE = 2 * FastMath.ulp(1d); // private final double relativeThreshold; // private final double absoluteThreshold; // // public BrentOptimizer(double rel, // double abs, // ConvergenceChecker<UnivariatePointValuePair> checker); // public BrentOptimizer(double rel, // double abs); // @Override // protected UnivariatePointValuePair doOptimize(); // private UnivariatePointValuePair best(UnivariatePointValuePair a, // UnivariatePointValuePair b, // boolean isMinim); // } // // // Abstract Java Test Class // package org.apache.commons.math3.optimization.univariate; // // import org.apache.commons.math3.analysis.QuinticFunction; // import org.apache.commons.math3.analysis.UnivariateFunction; // import org.apache.commons.math3.analysis.function.Sin; // import org.apache.commons.math3.analysis.function.StepFunction; // import org.apache.commons.math3.analysis.FunctionUtils; // import org.apache.commons.math3.exception.NumberIsTooLargeException; // import org.apache.commons.math3.exception.NumberIsTooSmallException; // import org.apache.commons.math3.exception.TooManyEvaluationsException; // import org.apache.commons.math3.optimization.ConvergenceChecker; // import org.apache.commons.math3.optimization.GoalType; // import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; // import org.apache.commons.math3.util.FastMath; // import org.junit.Assert; // import org.junit.Test; // // // // public final class BrentOptimizerTest { // // // @Test // public void testSinMin(); // @Test // public void testSinMinWithValueChecker(); // @Test // public void testBoundaries(); // @Test // public void testQuinticMin(); // @Test // public void testQuinticMinStatistics(); // @Test // public void testQuinticMax(); // @Test // public void testMinEndpoints(); // @Test // public void testMath832(); // @Test // public void testKeepInitIfBest(); // @Test // public void testMath855(); // public double value(double x); // public double value(double x); // } // You are a professional Java test case writer, please create a test case named `testKeepInitIfBest` for the `BrentOptimizer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Contrived example showing that prior to the resolution of MATH-855 * (second revision), the algorithm would not return the best point if * it happened to be the initial guess. */ @Test public void testKeepInitIfBest() {
/** * Contrived example showing that prior to the resolution of MATH-855 * (second revision), the algorithm would not return the best point if * it happened to be the initial guess. */
1
org.apache.commons.math3.optimization.univariate.BrentOptimizer
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.math3.optimization.univariate; import org.apache.commons.math3.util.Precision; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.optimization.ConvergenceChecker; import org.apache.commons.math3.optimization.GoalType; @Deprecated public class BrentOptimizer extends BaseAbstractUnivariateOptimizer { private static final double GOLDEN_SECTION = 0.5 * (3 - FastMath.sqrt(5)); private static final double MIN_RELATIVE_TOLERANCE = 2 * FastMath.ulp(1d); private final double relativeThreshold; private final double absoluteThreshold; public BrentOptimizer(double rel, double abs, ConvergenceChecker<UnivariatePointValuePair> checker); public BrentOptimizer(double rel, double abs); @Override protected UnivariatePointValuePair doOptimize(); private UnivariatePointValuePair best(UnivariatePointValuePair a, UnivariatePointValuePair b, boolean isMinim); } // Abstract Java Test Class package org.apache.commons.math3.optimization.univariate; import org.apache.commons.math3.analysis.QuinticFunction; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.function.Sin; import org.apache.commons.math3.analysis.function.StepFunction; import org.apache.commons.math3.analysis.FunctionUtils; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.exception.TooManyEvaluationsException; import org.apache.commons.math3.optimization.ConvergenceChecker; import org.apache.commons.math3.optimization.GoalType; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; public final class BrentOptimizerTest { @Test public void testSinMin(); @Test public void testSinMinWithValueChecker(); @Test public void testBoundaries(); @Test public void testQuinticMin(); @Test public void testQuinticMinStatistics(); @Test public void testQuinticMax(); @Test public void testMinEndpoints(); @Test public void testMath832(); @Test public void testKeepInitIfBest(); @Test public void testMath855(); public double value(double x); public double value(double x); } ``` You are a professional Java test case writer, please create a test case named `testKeepInitIfBest` for the `BrentOptimizer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Contrived example showing that prior to the resolution of MATH-855 * (second revision), the algorithm would not return the best point if * it happened to be the initial guess. */ @Test public void testKeepInitIfBest() { ```
@Deprecated public class BrentOptimizer extends BaseAbstractUnivariateOptimizer
package org.apache.commons.math3.optimization.univariate; import org.apache.commons.math3.analysis.QuinticFunction; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.function.Sin; import org.apache.commons.math3.analysis.function.StepFunction; import org.apache.commons.math3.analysis.FunctionUtils; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.exception.TooManyEvaluationsException; import org.apache.commons.math3.optimization.ConvergenceChecker; import org.apache.commons.math3.optimization.GoalType; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test;
@Test public void testSinMin(); @Test public void testSinMinWithValueChecker(); @Test public void testBoundaries(); @Test public void testQuinticMin(); @Test public void testQuinticMinStatistics(); @Test public void testQuinticMax(); @Test public void testMinEndpoints(); @Test public void testMath832(); @Test public void testKeepInitIfBest(); @Test public void testMath855(); public double value(double x); public double value(double x);
2f5c317817bcc5ec95056a3b9cbcdf64785309ecec8765ad59f75ddb6fea05f7
[ "org.apache.commons.math3.optimization.univariate.BrentOptimizerTest::testKeepInitIfBest" ]
private static final double GOLDEN_SECTION = 0.5 * (3 - FastMath.sqrt(5)); private static final double MIN_RELATIVE_TOLERANCE = 2 * FastMath.ulp(1d); private final double relativeThreshold; private final double absoluteThreshold;
@Test public void testKeepInitIfBest()
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.optimization.univariate; import org.apache.commons.math3.analysis.QuinticFunction; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.function.Sin; import org.apache.commons.math3.analysis.function.StepFunction; import org.apache.commons.math3.analysis.FunctionUtils; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.exception.TooManyEvaluationsException; import org.apache.commons.math3.optimization.ConvergenceChecker; import org.apache.commons.math3.optimization.GoalType; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; /** * @version $Id$ */ public final class BrentOptimizerTest { @Test public void testSinMin() { UnivariateFunction f = new Sin(); UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-14); Assert.assertEquals(3 * Math.PI / 2, optimizer.optimize(200, f, GoalType.MINIMIZE, 4, 5).getPoint(), 1e-8); Assert.assertTrue(optimizer.getEvaluations() <= 50); Assert.assertEquals(200, optimizer.getMaxEvaluations()); Assert.assertEquals(3 * Math.PI / 2, optimizer.optimize(200, f, GoalType.MINIMIZE, 1, 5).getPoint(), 1e-8); Assert.assertTrue(optimizer.getEvaluations() <= 100); Assert.assertTrue(optimizer.getEvaluations() >= 15); try { optimizer.optimize(10, f, GoalType.MINIMIZE, 4, 5); Assert.fail("an exception should have been thrown"); } catch (TooManyEvaluationsException fee) { // expected } } @Test public void testSinMinWithValueChecker() { final UnivariateFunction f = new Sin(); final ConvergenceChecker<UnivariatePointValuePair> checker = new SimpleUnivariateValueChecker(1e-5, 1e-14); // The default stopping criterion of Brent's algorithm should not // pass, but the search will stop at the given relative tolerance // for the function value. final UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-14, checker); final UnivariatePointValuePair result = optimizer.optimize(200, f, GoalType.MINIMIZE, 4, 5); Assert.assertEquals(3 * Math.PI / 2, result.getPoint(), 1e-3); } @Test public void testBoundaries() { final double lower = -1.0; final double upper = +1.0; UnivariateFunction f = new UnivariateFunction() { public double value(double x) { if (x < lower) { throw new NumberIsTooSmallException(x, lower, true); } else if (x > upper) { throw new NumberIsTooLargeException(x, upper, true); } else { return x; } } }; UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-14); Assert.assertEquals(lower, optimizer.optimize(100, f, GoalType.MINIMIZE, lower, upper).getPoint(), 1.0e-8); Assert.assertEquals(upper, optimizer.optimize(100, f, GoalType.MAXIMIZE, lower, upper).getPoint(), 1.0e-8); } @Test public void testQuinticMin() { // The function has local minima at -0.27195613 and 0.82221643. UnivariateFunction f = new QuinticFunction(); UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-14); Assert.assertEquals(-0.27195613, optimizer.optimize(200, f, GoalType.MINIMIZE, -0.3, -0.2).getPoint(), 1.0e-8); Assert.assertEquals( 0.82221643, optimizer.optimize(200, f, GoalType.MINIMIZE, 0.3, 0.9).getPoint(), 1.0e-8); Assert.assertTrue(optimizer.getEvaluations() <= 50); // search in a large interval Assert.assertEquals(-0.27195613, optimizer.optimize(200, f, GoalType.MINIMIZE, -1.0, 0.2).getPoint(), 1.0e-8); Assert.assertTrue(optimizer.getEvaluations() <= 50); } @Test public void testQuinticMinStatistics() { // The function has local minima at -0.27195613 and 0.82221643. UnivariateFunction f = new QuinticFunction(); UnivariateOptimizer optimizer = new BrentOptimizer(1e-11, 1e-14); final DescriptiveStatistics[] stat = new DescriptiveStatistics[2]; for (int i = 0; i < stat.length; i++) { stat[i] = new DescriptiveStatistics(); } final double min = -0.75; final double max = 0.25; final int nSamples = 200; final double delta = (max - min) / nSamples; for (int i = 0; i < nSamples; i++) { final double start = min + i * delta; stat[0].addValue(optimizer.optimize(40, f, GoalType.MINIMIZE, min, max, start).getPoint()); stat[1].addValue(optimizer.getEvaluations()); } final double meanOptValue = stat[0].getMean(); final double medianEval = stat[1].getPercentile(50); Assert.assertTrue(meanOptValue > -0.2719561281); Assert.assertTrue(meanOptValue < -0.2719561280); Assert.assertEquals(23, (int) medianEval); } @Test public void testQuinticMax() { // The quintic function has zeros at 0, +-0.5 and +-1. // The function has a local maximum at 0.27195613. UnivariateFunction f = new QuinticFunction(); UnivariateOptimizer optimizer = new BrentOptimizer(1e-12, 1e-14); Assert.assertEquals(0.27195613, optimizer.optimize(100, f, GoalType.MAXIMIZE, 0.2, 0.3).getPoint(), 1e-8); try { optimizer.optimize(5, f, GoalType.MAXIMIZE, 0.2, 0.3); Assert.fail("an exception should have been thrown"); } catch (TooManyEvaluationsException miee) { // expected } } @Test public void testMinEndpoints() { UnivariateFunction f = new Sin(); UnivariateOptimizer optimizer = new BrentOptimizer(1e-8, 1e-14); // endpoint is minimum double result = optimizer.optimize(50, f, GoalType.MINIMIZE, 3 * Math.PI / 2, 5).getPoint(); Assert.assertEquals(3 * Math.PI / 2, result, 1e-6); result = optimizer.optimize(50, f, GoalType.MINIMIZE, 4, 3 * Math.PI / 2).getPoint(); Assert.assertEquals(3 * Math.PI / 2, result, 1e-6); } @Test public void testMath832() { final UnivariateFunction f = new UnivariateFunction() { public double value(double x) { final double sqrtX = FastMath.sqrt(x); final double a = 1e2 * sqrtX; final double b = 1e6 / x; final double c = 1e4 / sqrtX; return a + b + c; } }; UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-8); final double result = optimizer.optimize(1483, f, GoalType.MINIMIZE, Double.MIN_VALUE, Double.MAX_VALUE).getPoint(); Assert.assertEquals(804.9355825, result, 1e-6); } /** * Contrived example showing that prior to the resolution of MATH-855 * (second revision), the algorithm would not return the best point if * it happened to be the initial guess. */ @Test public void testKeepInitIfBest() { final double minSin = 3 * Math.PI / 2; final double offset = 1e-8; final double delta = 1e-7; final UnivariateFunction f1 = new Sin(); final UnivariateFunction f2 = new StepFunction(new double[] { minSin, minSin + offset, minSin + 2 * offset}, new double[] { 0, -1, 0 }); final UnivariateFunction f = FunctionUtils.add(f1, f2); // A slightly less stringent tolerance would make the test pass // even with the previous implementation. final double relTol = 1e-8; final UnivariateOptimizer optimizer = new BrentOptimizer(relTol, 1e-100); final double init = minSin + 1.5 * offset; final UnivariatePointValuePair result = optimizer.optimize(200, f, GoalType.MINIMIZE, minSin - 6.789 * delta, minSin + 9.876 * delta, init); final int numEval = optimizer.getEvaluations(); final double sol = result.getPoint(); final double expected = init; // System.out.println("numEval=" + numEval); // System.out.println("min=" + init + " f=" + f.value(init)); // System.out.println("sol=" + sol + " f=" + f.value(sol)); // System.out.println("exp=" + expected + " f=" + f.value(expected)); Assert.assertTrue("Best point not reported", f.value(sol) <= f.value(expected)); } /** * Contrived example showing that prior to the resolution of MATH-855, * the algorithm, by always returning the last evaluated point, would * sometimes not report the best point it had found. */ @Test public void testMath855() { final double minSin = 3 * Math.PI / 2; final double offset = 1e-8; final double delta = 1e-7; final UnivariateFunction f1 = new Sin(); final UnivariateFunction f2 = new StepFunction(new double[] { minSin, minSin + offset, minSin + 5 * offset }, new double[] { 0, -1, 0 }); final UnivariateFunction f = FunctionUtils.add(f1, f2); final UnivariateOptimizer optimizer = new BrentOptimizer(1e-8, 1e-100); final UnivariatePointValuePair result = optimizer.optimize(200, f, GoalType.MINIMIZE, minSin - 6.789 * delta, minSin + 9.876 * delta); final int numEval = optimizer.getEvaluations(); final double sol = result.getPoint(); final double expected = 4.712389027602411; // System.out.println("min=" + (minSin + offset) + " f=" + f.value(minSin + offset)); // System.out.println("sol=" + sol + " f=" + f.value(sol)); // System.out.println("exp=" + expected + " f=" + f.value(expected)); Assert.assertTrue("Best point not reported", f.value(sol) <= f.value(expected)); } }
[ { "be_test_class_file": "org/apache/commons/math3/optimization/univariate/BrentOptimizer.java", "be_test_class_name": "org.apache.commons.math3.optimization.univariate.BrentOptimizer", "be_test_function_name": "best", "be_test_function_signature": "(Lorg/apache/commons/math3/optimization/univariate/UnivariatePointValuePair;Lorg/apache/commons/math3/optimization/univariate/UnivariatePointValuePair;Z)Lorg/apache/commons/math3/optimization/univariate/UnivariatePointValuePair;", "line_numbers": [ "304", "305", "307", "308", "311", "312", "314" ], "method_line_rate": 0.5714285714285714 }, { "be_test_class_file": "org/apache/commons/math3/optimization/univariate/BrentOptimizer.java", "be_test_class_name": "org.apache.commons.math3.optimization.univariate.BrentOptimizer", "be_test_function_name": "doOptimize", "be_test_function_signature": "()Lorg/apache/commons/math3/optimization/univariate/UnivariatePointValuePair;", "line_numbers": [ "118", "119", "120", "121", "124", "129", "130", "131", "133", "134", "137", "138", "139", "140", "141", "142", "143", "144", "146", "147", "149", "150", "153", "155", "157", "158", "159", "162", "163", "164", "165", "166", "167", "169", "170", "171", "172", "173", "175", "176", "178", "181", "182", "184", "188", "189", "192", "193", "194", "196", "201", "202", "204", "206", "210", "211", "213", "215", "219", "220", "221", "223", "226", "229", "230", "231", "235", "236", "237", "243", "244", "248", "249", "250", "252", "254", "255", "256", "257", "258", "259", "261", "262", "264", "266", "268", "269", "270", "271", "272", "275", "276", "279", "280", "286", "287" ], "method_line_rate": 0.7916666666666666 } ]
public final class FastFourierTransformerTest
@Test public void testAdHocData() { FastFourierTransformer transformer; transformer = new FastFourierTransformer(DftNormalization.STANDARD); Complex result[]; double tolerance = 1E-12; double x[] = {1.3, 2.4, 1.7, 4.1, 2.9, 1.7, 5.1, 2.7}; Complex y[] = { new Complex(21.9, 0.0), new Complex(-2.09497474683058, 1.91507575950825), new Complex(-2.6, 2.7), new Complex(-1.10502525316942, -4.88492424049175), new Complex(0.1, 0.0), new Complex(-1.10502525316942, 4.88492424049175), new Complex(-2.6, -2.7), new Complex(-2.09497474683058, -1.91507575950825)}; result = transformer.transform(x, TransformType.FORWARD); for (int i = 0; i < result.length; i++) { Assert.assertEquals(y[i].getReal(), result[i].getReal(), tolerance); Assert.assertEquals(y[i].getImaginary(), result[i].getImaginary(), tolerance); } result = transformer.transform(y, TransformType.INVERSE); for (int i = 0; i < result.length; i++) { Assert.assertEquals(x[i], result[i].getReal(), tolerance); Assert.assertEquals(0.0, result[i].getImaginary(), tolerance); } double x2[] = {10.4, 21.6, 40.8, 13.6, 23.2, 32.8, 13.6, 19.2}; TransformUtils.scaleArray(x2, 1.0 / FastMath.sqrt(x2.length)); Complex y2[] = y; transformer = new FastFourierTransformer(DftNormalization.UNITARY); result = transformer.transform(y2, TransformType.FORWARD); for (int i = 0; i < result.length; i++) { Assert.assertEquals(x2[i], result[i].getReal(), tolerance); Assert.assertEquals(0.0, result[i].getImaginary(), tolerance); } result = transformer.transform(x2, TransformType.INVERSE); for (int i = 0; i < result.length; i++) { Assert.assertEquals(y2[i].getReal(), result[i].getReal(), tolerance); Assert.assertEquals(y2[i].getImaginary(), result[i].getImaginary(), tolerance); } }
// , -0x1.921fb544387bap-18, -0x1.921fb544403c1p-19, -0x1.921fb544422c2p-20, -0x1.921fb54442a83p-21 // , -0x1.921fb54442c73p-22, -0x1.921fb54442cefp-23, -0x1.921fb54442d0ep-24, -0x1.921fb54442d15p-25 // , -0x1.921fb54442d17p-26, -0x1.921fb54442d18p-27, -0x1.921fb54442d18p-28, -0x1.921fb54442d18p-29 // , -0x1.921fb54442d18p-30, -0x1.921fb54442d18p-31, -0x1.921fb54442d18p-32, -0x1.921fb54442d18p-33 // , -0x1.921fb54442d18p-34, -0x1.921fb54442d18p-35, -0x1.921fb54442d18p-36, -0x1.921fb54442d18p-37 // , -0x1.921fb54442d18p-38, -0x1.921fb54442d18p-39, -0x1.921fb54442d18p-40, -0x1.921fb54442d18p-41 // , -0x1.921fb54442d18p-42, -0x1.921fb54442d18p-43, -0x1.921fb54442d18p-44, -0x1.921fb54442d18p-45 // , -0x1.921fb54442d18p-46, -0x1.921fb54442d18p-47, -0x1.921fb54442d18p-48, -0x1.921fb54442d18p-49 // , -0x1.921fb54442d18p-50, -0x1.921fb54442d18p-51, -0x1.921fb54442d18p-52, -0x1.921fb54442d18p-53 // , -0x1.921fb54442d18p-54, -0x1.921fb54442d18p-55, -0x1.921fb54442d18p-56, -0x1.921fb54442d18p-57 // , -0x1.921fb54442d18p-58, -0x1.921fb54442d18p-59, -0x1.921fb54442d18p-60 }; // private final DftNormalization normalization; // // public FastFourierTransformer(final DftNormalization normalization); // private static void bitReversalShuffle2(double[] a, double[] b); // private static void normalizeTransformedData(final double[][] dataRI, // final DftNormalization normalization, final TransformType type); // public static void transformInPlace(final double[][] dataRI, // final DftNormalization normalization, final TransformType type); // public Complex[] transform(final double[] f, final TransformType type); // public Complex[] transform(final UnivariateFunction f, // final double min, final double max, final int n, // final TransformType type); // public Complex[] transform(final Complex[] f, final TransformType type); // @Deprecated // public Object mdfft(Object mdca, TransformType type); // @Deprecated // private void mdfft(MultiDimensionalComplexMatrix mdcm, // TransformType type, int d, int[] subVector); // public MultiDimensionalComplexMatrix( // Object multiDimensionalComplexArray); // public Complex get(int... vector) // throws DimensionMismatchException; // public Complex set(Complex magnitude, int... vector) // throws DimensionMismatchException; // public int[] getDimensionSizes(); // public Object getArray(); // @Override // public Object clone(); // private void clone(MultiDimensionalComplexMatrix mdcm); // } // // // Abstract Java Test Class // package org.apache.commons.math3.transform; // // import java.util.Random; // import org.apache.commons.math3.analysis.UnivariateFunction; // import org.apache.commons.math3.analysis.function.Sin; // import org.apache.commons.math3.analysis.function.Sinc; // import org.apache.commons.math3.complex.Complex; // import org.apache.commons.math3.exception.MathIllegalArgumentException; // import org.apache.commons.math3.exception.NotStrictlyPositiveException; // import org.apache.commons.math3.exception.NumberIsTooLargeException; // import org.apache.commons.math3.util.FastMath; // import org.junit.Assert; // import org.junit.Test; // // // // public final class FastFourierTransformerTest { // private final static long SEED = 20110111L; // // @Test // public void testTransformComplexSizeNotAPowerOfTwo(); // @Test // public void testTransformRealSizeNotAPowerOfTwo(); // @Test // public void testTransformFunctionSizeNotAPowerOfTwo(); // @Test // public void testTransformFunctionNotStrictlyPositiveNumberOfSamples(); // @Test // public void testTransformFunctionInvalidBounds(); // private static Complex[] createComplexData(final int n); // private static double[] createRealData(final int n); // private static Complex[] dft(final Complex[] x, final int sgn); // private static void doTestTransformComplex(final int n, final double tol, // final DftNormalization normalization, // final TransformType type); // private static void doTestTransformReal(final int n, final double tol, // final DftNormalization normalization, // final TransformType type); // private static void doTestTransformFunction(final UnivariateFunction f, // final double min, final double max, int n, final double tol, // final DftNormalization normalization, // final TransformType type); // @Test // public void testTransformComplex(); // @Test // public void testStandardTransformReal(); // @Test // public void testStandardTransformFunction(); // @Test // public void testAdHocData(); // @Test // public void testSinFunction(); // @Test // public void test2DData(); // @Test // public void test2DDataUnitary(); // } // You are a professional Java test case writer, please create a test case named `testAdHocData` for the `FastFourierTransformer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test of transformer for the ad hoc data taken from Mathematica. */ /* * Additional tests for 1D data. */
src/test/java/org/apache/commons/math3/transform/FastFourierTransformerTest.java
package org.apache.commons.math3.transform; import java.io.Serializable; import java.lang.reflect.Array; import org.apache.commons.math3.analysis.FunctionUtils; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.complex.Complex; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.exception.MathIllegalStateException; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.util.ArithmeticUtils; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.MathArrays;
public FastFourierTransformer(final DftNormalization normalization); private static void bitReversalShuffle2(double[] a, double[] b); private static void normalizeTransformedData(final double[][] dataRI, final DftNormalization normalization, final TransformType type); public static void transformInPlace(final double[][] dataRI, final DftNormalization normalization, final TransformType type); public Complex[] transform(final double[] f, final TransformType type); public Complex[] transform(final UnivariateFunction f, final double min, final double max, final int n, final TransformType type); public Complex[] transform(final Complex[] f, final TransformType type); @Deprecated public Object mdfft(Object mdca, TransformType type); @Deprecated private void mdfft(MultiDimensionalComplexMatrix mdcm, TransformType type, int d, int[] subVector); public MultiDimensionalComplexMatrix( Object multiDimensionalComplexArray); public Complex get(int... vector) throws DimensionMismatchException; public Complex set(Complex magnitude, int... vector) throws DimensionMismatchException; public int[] getDimensionSizes(); public Object getArray(); @Override public Object clone(); private void clone(MultiDimensionalComplexMatrix mdcm);
447
testAdHocData
```java , -0x1.921fb544387bap-18, -0x1.921fb544403c1p-19, -0x1.921fb544422c2p-20, -0x1.921fb54442a83p-21 , -0x1.921fb54442c73p-22, -0x1.921fb54442cefp-23, -0x1.921fb54442d0ep-24, -0x1.921fb54442d15p-25 , -0x1.921fb54442d17p-26, -0x1.921fb54442d18p-27, -0x1.921fb54442d18p-28, -0x1.921fb54442d18p-29 , -0x1.921fb54442d18p-30, -0x1.921fb54442d18p-31, -0x1.921fb54442d18p-32, -0x1.921fb54442d18p-33 , -0x1.921fb54442d18p-34, -0x1.921fb54442d18p-35, -0x1.921fb54442d18p-36, -0x1.921fb54442d18p-37 , -0x1.921fb54442d18p-38, -0x1.921fb54442d18p-39, -0x1.921fb54442d18p-40, -0x1.921fb54442d18p-41 , -0x1.921fb54442d18p-42, -0x1.921fb54442d18p-43, -0x1.921fb54442d18p-44, -0x1.921fb54442d18p-45 , -0x1.921fb54442d18p-46, -0x1.921fb54442d18p-47, -0x1.921fb54442d18p-48, -0x1.921fb54442d18p-49 , -0x1.921fb54442d18p-50, -0x1.921fb54442d18p-51, -0x1.921fb54442d18p-52, -0x1.921fb54442d18p-53 , -0x1.921fb54442d18p-54, -0x1.921fb54442d18p-55, -0x1.921fb54442d18p-56, -0x1.921fb54442d18p-57 , -0x1.921fb54442d18p-58, -0x1.921fb54442d18p-59, -0x1.921fb54442d18p-60 }; private final DftNormalization normalization; public FastFourierTransformer(final DftNormalization normalization); private static void bitReversalShuffle2(double[] a, double[] b); private static void normalizeTransformedData(final double[][] dataRI, final DftNormalization normalization, final TransformType type); public static void transformInPlace(final double[][] dataRI, final DftNormalization normalization, final TransformType type); public Complex[] transform(final double[] f, final TransformType type); public Complex[] transform(final UnivariateFunction f, final double min, final double max, final int n, final TransformType type); public Complex[] transform(final Complex[] f, final TransformType type); @Deprecated public Object mdfft(Object mdca, TransformType type); @Deprecated private void mdfft(MultiDimensionalComplexMatrix mdcm, TransformType type, int d, int[] subVector); public MultiDimensionalComplexMatrix( Object multiDimensionalComplexArray); public Complex get(int... vector) throws DimensionMismatchException; public Complex set(Complex magnitude, int... vector) throws DimensionMismatchException; public int[] getDimensionSizes(); public Object getArray(); @Override public Object clone(); private void clone(MultiDimensionalComplexMatrix mdcm); } // Abstract Java Test Class package org.apache.commons.math3.transform; import java.util.Random; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.function.Sin; import org.apache.commons.math3.analysis.function.Sinc; import org.apache.commons.math3.complex.Complex; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; public final class FastFourierTransformerTest { private final static long SEED = 20110111L; @Test public void testTransformComplexSizeNotAPowerOfTwo(); @Test public void testTransformRealSizeNotAPowerOfTwo(); @Test public void testTransformFunctionSizeNotAPowerOfTwo(); @Test public void testTransformFunctionNotStrictlyPositiveNumberOfSamples(); @Test public void testTransformFunctionInvalidBounds(); private static Complex[] createComplexData(final int n); private static double[] createRealData(final int n); private static Complex[] dft(final Complex[] x, final int sgn); private static void doTestTransformComplex(final int n, final double tol, final DftNormalization normalization, final TransformType type); private static void doTestTransformReal(final int n, final double tol, final DftNormalization normalization, final TransformType type); private static void doTestTransformFunction(final UnivariateFunction f, final double min, final double max, int n, final double tol, final DftNormalization normalization, final TransformType type); @Test public void testTransformComplex(); @Test public void testStandardTransformReal(); @Test public void testStandardTransformFunction(); @Test public void testAdHocData(); @Test public void testSinFunction(); @Test public void test2DData(); @Test public void test2DDataUnitary(); } ``` You are a professional Java test case writer, please create a test case named `testAdHocData` for the `FastFourierTransformer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test of transformer for the ad hoc data taken from Mathematica. */ /* * Additional tests for 1D data. */
402
// , -0x1.921fb544387bap-18, -0x1.921fb544403c1p-19, -0x1.921fb544422c2p-20, -0x1.921fb54442a83p-21 // , -0x1.921fb54442c73p-22, -0x1.921fb54442cefp-23, -0x1.921fb54442d0ep-24, -0x1.921fb54442d15p-25 // , -0x1.921fb54442d17p-26, -0x1.921fb54442d18p-27, -0x1.921fb54442d18p-28, -0x1.921fb54442d18p-29 // , -0x1.921fb54442d18p-30, -0x1.921fb54442d18p-31, -0x1.921fb54442d18p-32, -0x1.921fb54442d18p-33 // , -0x1.921fb54442d18p-34, -0x1.921fb54442d18p-35, -0x1.921fb54442d18p-36, -0x1.921fb54442d18p-37 // , -0x1.921fb54442d18p-38, -0x1.921fb54442d18p-39, -0x1.921fb54442d18p-40, -0x1.921fb54442d18p-41 // , -0x1.921fb54442d18p-42, -0x1.921fb54442d18p-43, -0x1.921fb54442d18p-44, -0x1.921fb54442d18p-45 // , -0x1.921fb54442d18p-46, -0x1.921fb54442d18p-47, -0x1.921fb54442d18p-48, -0x1.921fb54442d18p-49 // , -0x1.921fb54442d18p-50, -0x1.921fb54442d18p-51, -0x1.921fb54442d18p-52, -0x1.921fb54442d18p-53 // , -0x1.921fb54442d18p-54, -0x1.921fb54442d18p-55, -0x1.921fb54442d18p-56, -0x1.921fb54442d18p-57 // , -0x1.921fb54442d18p-58, -0x1.921fb54442d18p-59, -0x1.921fb54442d18p-60 }; // private final DftNormalization normalization; // // public FastFourierTransformer(final DftNormalization normalization); // private static void bitReversalShuffle2(double[] a, double[] b); // private static void normalizeTransformedData(final double[][] dataRI, // final DftNormalization normalization, final TransformType type); // public static void transformInPlace(final double[][] dataRI, // final DftNormalization normalization, final TransformType type); // public Complex[] transform(final double[] f, final TransformType type); // public Complex[] transform(final UnivariateFunction f, // final double min, final double max, final int n, // final TransformType type); // public Complex[] transform(final Complex[] f, final TransformType type); // @Deprecated // public Object mdfft(Object mdca, TransformType type); // @Deprecated // private void mdfft(MultiDimensionalComplexMatrix mdcm, // TransformType type, int d, int[] subVector); // public MultiDimensionalComplexMatrix( // Object multiDimensionalComplexArray); // public Complex get(int... vector) // throws DimensionMismatchException; // public Complex set(Complex magnitude, int... vector) // throws DimensionMismatchException; // public int[] getDimensionSizes(); // public Object getArray(); // @Override // public Object clone(); // private void clone(MultiDimensionalComplexMatrix mdcm); // } // // // Abstract Java Test Class // package org.apache.commons.math3.transform; // // import java.util.Random; // import org.apache.commons.math3.analysis.UnivariateFunction; // import org.apache.commons.math3.analysis.function.Sin; // import org.apache.commons.math3.analysis.function.Sinc; // import org.apache.commons.math3.complex.Complex; // import org.apache.commons.math3.exception.MathIllegalArgumentException; // import org.apache.commons.math3.exception.NotStrictlyPositiveException; // import org.apache.commons.math3.exception.NumberIsTooLargeException; // import org.apache.commons.math3.util.FastMath; // import org.junit.Assert; // import org.junit.Test; // // // // public final class FastFourierTransformerTest { // private final static long SEED = 20110111L; // // @Test // public void testTransformComplexSizeNotAPowerOfTwo(); // @Test // public void testTransformRealSizeNotAPowerOfTwo(); // @Test // public void testTransformFunctionSizeNotAPowerOfTwo(); // @Test // public void testTransformFunctionNotStrictlyPositiveNumberOfSamples(); // @Test // public void testTransformFunctionInvalidBounds(); // private static Complex[] createComplexData(final int n); // private static double[] createRealData(final int n); // private static Complex[] dft(final Complex[] x, final int sgn); // private static void doTestTransformComplex(final int n, final double tol, // final DftNormalization normalization, // final TransformType type); // private static void doTestTransformReal(final int n, final double tol, // final DftNormalization normalization, // final TransformType type); // private static void doTestTransformFunction(final UnivariateFunction f, // final double min, final double max, int n, final double tol, // final DftNormalization normalization, // final TransformType type); // @Test // public void testTransformComplex(); // @Test // public void testStandardTransformReal(); // @Test // public void testStandardTransformFunction(); // @Test // public void testAdHocData(); // @Test // public void testSinFunction(); // @Test // public void test2DData(); // @Test // public void test2DDataUnitary(); // } // You are a professional Java test case writer, please create a test case named `testAdHocData` for the `FastFourierTransformer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test of transformer for the ad hoc data taken from Mathematica. */ /* * Additional tests for 1D data. */ @Test public void testAdHocData() {
/** * Test of transformer for the ad hoc data taken from Mathematica. */ /* * Additional tests for 1D data. */
1
org.apache.commons.math3.transform.FastFourierTransformer
src/test/java
```java , -0x1.921fb544387bap-18, -0x1.921fb544403c1p-19, -0x1.921fb544422c2p-20, -0x1.921fb54442a83p-21 , -0x1.921fb54442c73p-22, -0x1.921fb54442cefp-23, -0x1.921fb54442d0ep-24, -0x1.921fb54442d15p-25 , -0x1.921fb54442d17p-26, -0x1.921fb54442d18p-27, -0x1.921fb54442d18p-28, -0x1.921fb54442d18p-29 , -0x1.921fb54442d18p-30, -0x1.921fb54442d18p-31, -0x1.921fb54442d18p-32, -0x1.921fb54442d18p-33 , -0x1.921fb54442d18p-34, -0x1.921fb54442d18p-35, -0x1.921fb54442d18p-36, -0x1.921fb54442d18p-37 , -0x1.921fb54442d18p-38, -0x1.921fb54442d18p-39, -0x1.921fb54442d18p-40, -0x1.921fb54442d18p-41 , -0x1.921fb54442d18p-42, -0x1.921fb54442d18p-43, -0x1.921fb54442d18p-44, -0x1.921fb54442d18p-45 , -0x1.921fb54442d18p-46, -0x1.921fb54442d18p-47, -0x1.921fb54442d18p-48, -0x1.921fb54442d18p-49 , -0x1.921fb54442d18p-50, -0x1.921fb54442d18p-51, -0x1.921fb54442d18p-52, -0x1.921fb54442d18p-53 , -0x1.921fb54442d18p-54, -0x1.921fb54442d18p-55, -0x1.921fb54442d18p-56, -0x1.921fb54442d18p-57 , -0x1.921fb54442d18p-58, -0x1.921fb54442d18p-59, -0x1.921fb54442d18p-60 }; private final DftNormalization normalization; public FastFourierTransformer(final DftNormalization normalization); private static void bitReversalShuffle2(double[] a, double[] b); private static void normalizeTransformedData(final double[][] dataRI, final DftNormalization normalization, final TransformType type); public static void transformInPlace(final double[][] dataRI, final DftNormalization normalization, final TransformType type); public Complex[] transform(final double[] f, final TransformType type); public Complex[] transform(final UnivariateFunction f, final double min, final double max, final int n, final TransformType type); public Complex[] transform(final Complex[] f, final TransformType type); @Deprecated public Object mdfft(Object mdca, TransformType type); @Deprecated private void mdfft(MultiDimensionalComplexMatrix mdcm, TransformType type, int d, int[] subVector); public MultiDimensionalComplexMatrix( Object multiDimensionalComplexArray); public Complex get(int... vector) throws DimensionMismatchException; public Complex set(Complex magnitude, int... vector) throws DimensionMismatchException; public int[] getDimensionSizes(); public Object getArray(); @Override public Object clone(); private void clone(MultiDimensionalComplexMatrix mdcm); } // Abstract Java Test Class package org.apache.commons.math3.transform; import java.util.Random; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.function.Sin; import org.apache.commons.math3.analysis.function.Sinc; import org.apache.commons.math3.complex.Complex; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; public final class FastFourierTransformerTest { private final static long SEED = 20110111L; @Test public void testTransformComplexSizeNotAPowerOfTwo(); @Test public void testTransformRealSizeNotAPowerOfTwo(); @Test public void testTransformFunctionSizeNotAPowerOfTwo(); @Test public void testTransformFunctionNotStrictlyPositiveNumberOfSamples(); @Test public void testTransformFunctionInvalidBounds(); private static Complex[] createComplexData(final int n); private static double[] createRealData(final int n); private static Complex[] dft(final Complex[] x, final int sgn); private static void doTestTransformComplex(final int n, final double tol, final DftNormalization normalization, final TransformType type); private static void doTestTransformReal(final int n, final double tol, final DftNormalization normalization, final TransformType type); private static void doTestTransformFunction(final UnivariateFunction f, final double min, final double max, int n, final double tol, final DftNormalization normalization, final TransformType type); @Test public void testTransformComplex(); @Test public void testStandardTransformReal(); @Test public void testStandardTransformFunction(); @Test public void testAdHocData(); @Test public void testSinFunction(); @Test public void test2DData(); @Test public void test2DDataUnitary(); } ``` You are a professional Java test case writer, please create a test case named `testAdHocData` for the `FastFourierTransformer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test of transformer for the ad hoc data taken from Mathematica. */ /* * Additional tests for 1D data. */ @Test public void testAdHocData() { ```
public class FastFourierTransformer implements Serializable
package org.apache.commons.math3.transform; import java.util.Random; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.function.Sin; import org.apache.commons.math3.analysis.function.Sinc; import org.apache.commons.math3.complex.Complex; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test;
@Test public void testTransformComplexSizeNotAPowerOfTwo(); @Test public void testTransformRealSizeNotAPowerOfTwo(); @Test public void testTransformFunctionSizeNotAPowerOfTwo(); @Test public void testTransformFunctionNotStrictlyPositiveNumberOfSamples(); @Test public void testTransformFunctionInvalidBounds(); private static Complex[] createComplexData(final int n); private static double[] createRealData(final int n); private static Complex[] dft(final Complex[] x, final int sgn); private static void doTestTransformComplex(final int n, final double tol, final DftNormalization normalization, final TransformType type); private static void doTestTransformReal(final int n, final double tol, final DftNormalization normalization, final TransformType type); private static void doTestTransformFunction(final UnivariateFunction f, final double min, final double max, int n, final double tol, final DftNormalization normalization, final TransformType type); @Test public void testTransformComplex(); @Test public void testStandardTransformReal(); @Test public void testStandardTransformFunction(); @Test public void testAdHocData(); @Test public void testSinFunction(); @Test public void test2DData(); @Test public void test2DDataUnitary();
30728b1eef14a40f01252c336e18d0b6d5483ca7baef9f6a5d2526a70811ba75
[ "org.apache.commons.math3.transform.FastFourierTransformerTest::testAdHocData" ]
static final long serialVersionUID = 20120210L; private static final double[] W_SUB_N_R = { 0x1.0p0, -0x1.0p0, 0x1.1a62633145c07p-54, 0x1.6a09e667f3bcdp-1 , 0x1.d906bcf328d46p-1, 0x1.f6297cff75cbp-1, 0x1.fd88da3d12526p-1, 0x1.ff621e3796d7ep-1 , 0x1.ffd886084cd0dp-1, 0x1.fff62169b92dbp-1, 0x1.fffd8858e8a92p-1, 0x1.ffff621621d02p-1 , 0x1.ffffd88586ee6p-1, 0x1.fffff62161a34p-1, 0x1.fffffd8858675p-1, 0x1.ffffff621619cp-1 , 0x1.ffffffd885867p-1, 0x1.fffffff62161ap-1, 0x1.fffffffd88586p-1, 0x1.ffffffff62162p-1 , 0x1.ffffffffd8858p-1, 0x1.fffffffff6216p-1, 0x1.fffffffffd886p-1, 0x1.ffffffffff621p-1 , 0x1.ffffffffffd88p-1, 0x1.fffffffffff62p-1, 0x1.fffffffffffd9p-1, 0x1.ffffffffffff6p-1 , 0x1.ffffffffffffep-1, 0x1.fffffffffffffp-1, 0x1.0p0, 0x1.0p0 , 0x1.0p0, 0x1.0p0, 0x1.0p0, 0x1.0p0 , 0x1.0p0, 0x1.0p0, 0x1.0p0, 0x1.0p0 , 0x1.0p0, 0x1.0p0, 0x1.0p0, 0x1.0p0 , 0x1.0p0, 0x1.0p0, 0x1.0p0, 0x1.0p0 , 0x1.0p0, 0x1.0p0, 0x1.0p0, 0x1.0p0 , 0x1.0p0, 0x1.0p0, 0x1.0p0, 0x1.0p0 , 0x1.0p0, 0x1.0p0, 0x1.0p0, 0x1.0p0 , 0x1.0p0, 0x1.0p0, 0x1.0p0 }; private static final double[] W_SUB_N_I = { 0x1.1a62633145c07p-52, -0x1.1a62633145c07p-53, -0x1.0p0, -0x1.6a09e667f3bccp-1 , -0x1.87de2a6aea963p-2, -0x1.8f8b83c69a60ap-3, -0x1.917a6bc29b42cp-4, -0x1.91f65f10dd814p-5 , -0x1.92155f7a3667ep-6, -0x1.921d1fcdec784p-7, -0x1.921f0fe670071p-8, -0x1.921f8becca4bap-9 , -0x1.921faaee6472dp-10, -0x1.921fb2aecb36p-11, -0x1.921fb49ee4ea6p-12, -0x1.921fb51aeb57bp-13 , -0x1.921fb539ecf31p-14, -0x1.921fb541ad59ep-15, -0x1.921fb5439d73ap-16, -0x1.921fb544197ap-17 , -0x1.921fb544387bap-18, -0x1.921fb544403c1p-19, -0x1.921fb544422c2p-20, -0x1.921fb54442a83p-21 , -0x1.921fb54442c73p-22, -0x1.921fb54442cefp-23, -0x1.921fb54442d0ep-24, -0x1.921fb54442d15p-25 , -0x1.921fb54442d17p-26, -0x1.921fb54442d18p-27, -0x1.921fb54442d18p-28, -0x1.921fb54442d18p-29 , -0x1.921fb54442d18p-30, -0x1.921fb54442d18p-31, -0x1.921fb54442d18p-32, -0x1.921fb54442d18p-33 , -0x1.921fb54442d18p-34, -0x1.921fb54442d18p-35, -0x1.921fb54442d18p-36, -0x1.921fb54442d18p-37 , -0x1.921fb54442d18p-38, -0x1.921fb54442d18p-39, -0x1.921fb54442d18p-40, -0x1.921fb54442d18p-41 , -0x1.921fb54442d18p-42, -0x1.921fb54442d18p-43, -0x1.921fb54442d18p-44, -0x1.921fb54442d18p-45 , -0x1.921fb54442d18p-46, -0x1.921fb54442d18p-47, -0x1.921fb54442d18p-48, -0x1.921fb54442d18p-49 , -0x1.921fb54442d18p-50, -0x1.921fb54442d18p-51, -0x1.921fb54442d18p-52, -0x1.921fb54442d18p-53 , -0x1.921fb54442d18p-54, -0x1.921fb54442d18p-55, -0x1.921fb54442d18p-56, -0x1.921fb54442d18p-57 , -0x1.921fb54442d18p-58, -0x1.921fb54442d18p-59, -0x1.921fb54442d18p-60 }; private final DftNormalization normalization;
@Test public void testAdHocData()
private final static long SEED = 20110111L;
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.transform; import java.util.Random; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.function.Sin; import org.apache.commons.math3.analysis.function.Sinc; import org.apache.commons.math3.complex.Complex; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; /** * Test case for fast Fourier transformer. * <p> * FFT algorithm is exact, the small tolerance number is used only * to account for round-off errors. * * @version $Id$ */ public final class FastFourierTransformerTest { /** The common seed of all random number generators used in this test. */ private final static long SEED = 20110111L; /* * Precondition checks. */ @Test public void testTransformComplexSizeNotAPowerOfTwo() { final int n = 127; final Complex[] x = createComplexData(n); final DftNormalization[] norm; norm = DftNormalization.values(); final TransformType[] type; type = TransformType.values(); for (int i = 0; i < norm.length; i++) { for (int j = 0; j < type.length; j++) { final FastFourierTransformer fft; fft = new FastFourierTransformer(norm[i]); try { fft.transform(x, type[j]); Assert.fail(norm[i] + ", " + type[j] + ": MathIllegalArgumentException was expected"); } catch (MathIllegalArgumentException e) { // Expected behaviour } } } } @Test public void testTransformRealSizeNotAPowerOfTwo() { final int n = 127; final double[] x = createRealData(n); final DftNormalization[] norm; norm = DftNormalization.values(); final TransformType[] type; type = TransformType.values(); for (int i = 0; i < norm.length; i++) { for (int j = 0; j < type.length; j++) { final FastFourierTransformer fft; fft = new FastFourierTransformer(norm[i]); try { fft.transform(x, type[j]); Assert.fail(norm[i] + ", " + type[j] + ": MathIllegalArgumentException was expected"); } catch (MathIllegalArgumentException e) { // Expected behaviour } } } } @Test public void testTransformFunctionSizeNotAPowerOfTwo() { final int n = 127; final UnivariateFunction f = new Sin(); final DftNormalization[] norm; norm = DftNormalization.values(); final TransformType[] type; type = TransformType.values(); for (int i = 0; i < norm.length; i++) { for (int j = 0; j < type.length; j++) { final FastFourierTransformer fft; fft = new FastFourierTransformer(norm[i]); try { fft.transform(f, 0.0, Math.PI, n, type[j]); Assert.fail(norm[i] + ", " + type[j] + ": MathIllegalArgumentException was expected"); } catch (MathIllegalArgumentException e) { // Expected behaviour } } } } @Test public void testTransformFunctionNotStrictlyPositiveNumberOfSamples() { final int n = -128; final UnivariateFunction f = new Sin(); final DftNormalization[] norm; norm = DftNormalization.values(); final TransformType[] type; type = TransformType.values(); for (int i = 0; i < norm.length; i++) { for (int j = 0; j < type.length; j++) { final FastFourierTransformer fft; fft = new FastFourierTransformer(norm[i]); try { fft.transform(f, 0.0, Math.PI, n, type[j]); fft.transform(f, 0.0, Math.PI, n, type[j]); Assert.fail(norm[i] + ", " + type[j] + ": NotStrictlyPositiveException was expected"); } catch (NotStrictlyPositiveException e) { // Expected behaviour } } } } @Test public void testTransformFunctionInvalidBounds() { final int n = 128; final UnivariateFunction f = new Sin(); final DftNormalization[] norm; norm = DftNormalization.values(); final TransformType[] type; type = TransformType.values(); for (int i = 0; i < norm.length; i++) { for (int j = 0; j < type.length; j++) { final FastFourierTransformer fft; fft = new FastFourierTransformer(norm[i]); try { fft.transform(f, Math.PI, 0.0, n, type[j]); Assert.fail(norm[i] + ", " + type[j] + ": NumberIsTooLargeException was expected"); } catch (NumberIsTooLargeException e) { // Expected behaviour } } } } /* * Utility methods for checking (successful) transforms. */ private static Complex[] createComplexData(final int n) { final Random random = new Random(SEED); final Complex[] data = new Complex[n]; for (int i = 0; i < n; i++) { final double re = 2.0 * random.nextDouble() - 1.0; final double im = 2.0 * random.nextDouble() - 1.0; data[i] = new Complex(re, im); } return data; } private static double[] createRealData(final int n) { final Random random = new Random(SEED); final double[] data = new double[n]; for (int i = 0; i < n; i++) { data[i] = 2.0 * random.nextDouble() - 1.0; } return data; } /** Naive implementation of DFT, for reference. */ private static Complex[] dft(final Complex[] x, final int sgn) { final int n = x.length; final double[] cos = new double[n]; final double[] sin = new double[n]; final Complex[] y = new Complex[n]; for (int i = 0; i < n; i++) { final double arg = 2.0 * FastMath.PI * i / n; cos[i] = FastMath.cos(arg); sin[i] = FastMath.sin(arg); } for (int i = 0; i < n; i++) { double yr = 0.0; double yi = 0.0; for (int j = 0; j < n; j++) { final int index = (i * j) % n; final double c = cos[index]; final double s = sin[index]; final double xr = x[j].getReal(); final double xi = x[j].getImaginary(); yr += c * xr - sgn * s * xi; yi += sgn * s * xr + c * xi; } y[i] = new Complex(yr, yi); } return y; } private static void doTestTransformComplex(final int n, final double tol, final DftNormalization normalization, final TransformType type) { final FastFourierTransformer fft; fft = new FastFourierTransformer(normalization); final Complex[] x = createComplexData(n); final Complex[] expected; final double s; if (type==TransformType.FORWARD) { expected = dft(x, -1); if (normalization == DftNormalization.STANDARD){ s = 1.0; } else { s = 1.0 / FastMath.sqrt(n); } } else { expected = dft(x, 1); if (normalization == DftNormalization.STANDARD) { s = 1.0 / n; } else { s = 1.0 / FastMath.sqrt(n); } } final Complex[] actual = fft.transform(x, type); for (int i = 0; i < n; i++) { final String msg; msg = String.format("%s, %s, %d, %d", normalization, type, n, i); final double re = s * expected[i].getReal(); Assert.assertEquals(msg, re, actual[i].getReal(), tol * FastMath.abs(re)); final double im = s * expected[i].getImaginary(); Assert.assertEquals(msg, im, actual[i].getImaginary(), tol * FastMath.abs(re)); } } private static void doTestTransformReal(final int n, final double tol, final DftNormalization normalization, final TransformType type) { final FastFourierTransformer fft; fft = new FastFourierTransformer(normalization); final double[] x = createRealData(n); final Complex[] xc = new Complex[n]; for (int i = 0; i < n; i++) { xc[i] = new Complex(x[i], 0.0); } final Complex[] expected; final double s; if (type == TransformType.FORWARD) { expected = dft(xc, -1); if (normalization == DftNormalization.STANDARD) { s = 1.0; } else { s = 1.0 / FastMath.sqrt(n); } } else { expected = dft(xc, 1); if (normalization == DftNormalization.STANDARD) { s = 1.0 / n; } else { s = 1.0 / FastMath.sqrt(n); } } final Complex[] actual = fft.transform(x, type); for (int i = 0; i < n; i++) { final String msg; msg = String.format("%s, %s, %d, %d", normalization, type, n, i); final double re = s * expected[i].getReal(); Assert.assertEquals(msg, re, actual[i].getReal(), tol * FastMath.abs(re)); final double im = s * expected[i].getImaginary(); Assert.assertEquals(msg, im, actual[i].getImaginary(), tol * FastMath.abs(re)); } } private static void doTestTransformFunction(final UnivariateFunction f, final double min, final double max, int n, final double tol, final DftNormalization normalization, final TransformType type) { final FastFourierTransformer fft; fft = new FastFourierTransformer(normalization); final Complex[] x = new Complex[n]; for (int i = 0; i < n; i++) { final double t = min + i * (max - min) / n; x[i] = new Complex(f.value(t)); } final Complex[] expected; final double s; if (type == TransformType.FORWARD) { expected = dft(x, -1); if (normalization == DftNormalization.STANDARD) { s = 1.0; } else { s = 1.0 / FastMath.sqrt(n); } } else { expected = dft(x, 1); if (normalization == DftNormalization.STANDARD) { s = 1.0 / n; } else { s = 1.0 / FastMath.sqrt(n); } } final Complex[] actual = fft.transform(f, min, max, n, type); for (int i = 0; i < n; i++) { final String msg = String.format("%d, %d", n, i); final double re = s * expected[i].getReal(); Assert.assertEquals(msg, re, actual[i].getReal(), tol * FastMath.abs(re)); final double im = s * expected[i].getImaginary(); Assert.assertEquals(msg, im, actual[i].getImaginary(), tol * FastMath.abs(re)); } } /* * Tests of standard transform (when data is valid). */ @Test public void testTransformComplex() { final DftNormalization[] norm; norm = DftNormalization.values(); final TransformType[] type; type = TransformType.values(); for (int i = 0; i < norm.length; i++) { for (int j = 0; j < type.length; j++) { doTestTransformComplex(2, 1.0E-15, norm[i], type[j]); doTestTransformComplex(4, 1.0E-14, norm[i], type[j]); doTestTransformComplex(8, 1.0E-14, norm[i], type[j]); doTestTransformComplex(16, 1.0E-13, norm[i], type[j]); doTestTransformComplex(32, 1.0E-13, norm[i], type[j]); doTestTransformComplex(64, 1.0E-12, norm[i], type[j]); doTestTransformComplex(128, 1.0E-12, norm[i], type[j]); } } } @Test public void testStandardTransformReal() { final DftNormalization[] norm; norm = DftNormalization.values(); final TransformType[] type; type = TransformType.values(); for (int i = 0; i < norm.length; i++) { for (int j = 0; j < type.length; j++) { doTestTransformReal(2, 1.0E-15, norm[i], type[j]); doTestTransformReal(4, 1.0E-14, norm[i], type[j]); doTestTransformReal(8, 1.0E-14, norm[i], type[j]); doTestTransformReal(16, 1.0E-13, norm[i], type[j]); doTestTransformReal(32, 1.0E-13, norm[i], type[j]); doTestTransformReal(64, 1.0E-13, norm[i], type[j]); doTestTransformReal(128, 1.0E-11, norm[i], type[j]); } } } @Test public void testStandardTransformFunction() { final UnivariateFunction f = new Sinc(); final double min = -FastMath.PI; final double max = FastMath.PI; final DftNormalization[] norm; norm = DftNormalization.values(); final TransformType[] type; type = TransformType.values(); for (int i = 0; i < norm.length; i++) { for (int j = 0; j < type.length; j++) { doTestTransformFunction(f, min, max, 2, 1.0E-15, norm[i], type[j]); doTestTransformFunction(f, min, max, 4, 1.0E-14, norm[i], type[j]); doTestTransformFunction(f, min, max, 8, 1.0E-14, norm[i], type[j]); doTestTransformFunction(f, min, max, 16, 1.0E-13, norm[i], type[j]); doTestTransformFunction(f, min, max, 32, 1.0E-13, norm[i], type[j]); doTestTransformFunction(f, min, max, 64, 1.0E-12, norm[i], type[j]); doTestTransformFunction(f, min, max, 128, 1.0E-11, norm[i], type[j]); } } } /* * Additional tests for 1D data. */ /** * Test of transformer for the ad hoc data taken from Mathematica. */ @Test public void testAdHocData() { FastFourierTransformer transformer; transformer = new FastFourierTransformer(DftNormalization.STANDARD); Complex result[]; double tolerance = 1E-12; double x[] = {1.3, 2.4, 1.7, 4.1, 2.9, 1.7, 5.1, 2.7}; Complex y[] = { new Complex(21.9, 0.0), new Complex(-2.09497474683058, 1.91507575950825), new Complex(-2.6, 2.7), new Complex(-1.10502525316942, -4.88492424049175), new Complex(0.1, 0.0), new Complex(-1.10502525316942, 4.88492424049175), new Complex(-2.6, -2.7), new Complex(-2.09497474683058, -1.91507575950825)}; result = transformer.transform(x, TransformType.FORWARD); for (int i = 0; i < result.length; i++) { Assert.assertEquals(y[i].getReal(), result[i].getReal(), tolerance); Assert.assertEquals(y[i].getImaginary(), result[i].getImaginary(), tolerance); } result = transformer.transform(y, TransformType.INVERSE); for (int i = 0; i < result.length; i++) { Assert.assertEquals(x[i], result[i].getReal(), tolerance); Assert.assertEquals(0.0, result[i].getImaginary(), tolerance); } double x2[] = {10.4, 21.6, 40.8, 13.6, 23.2, 32.8, 13.6, 19.2}; TransformUtils.scaleArray(x2, 1.0 / FastMath.sqrt(x2.length)); Complex y2[] = y; transformer = new FastFourierTransformer(DftNormalization.UNITARY); result = transformer.transform(y2, TransformType.FORWARD); for (int i = 0; i < result.length; i++) { Assert.assertEquals(x2[i], result[i].getReal(), tolerance); Assert.assertEquals(0.0, result[i].getImaginary(), tolerance); } result = transformer.transform(x2, TransformType.INVERSE); for (int i = 0; i < result.length; i++) { Assert.assertEquals(y2[i].getReal(), result[i].getReal(), tolerance); Assert.assertEquals(y2[i].getImaginary(), result[i].getImaginary(), tolerance); } } /** * Test of transformer for the sine function. */ @Test public void testSinFunction() { UnivariateFunction f = new Sin(); FastFourierTransformer transformer; transformer = new FastFourierTransformer(DftNormalization.STANDARD); Complex result[]; int N = 1 << 8; double min, max, tolerance = 1E-12; min = 0.0; max = 2.0 * FastMath.PI; result = transformer.transform(f, min, max, N, TransformType.FORWARD); Assert.assertEquals(0.0, result[1].getReal(), tolerance); Assert.assertEquals(-(N >> 1), result[1].getImaginary(), tolerance); Assert.assertEquals(0.0, result[N-1].getReal(), tolerance); Assert.assertEquals(N >> 1, result[N-1].getImaginary(), tolerance); for (int i = 0; i < N-1; i += (i == 0 ? 2 : 1)) { Assert.assertEquals(0.0, result[i].getReal(), tolerance); Assert.assertEquals(0.0, result[i].getImaginary(), tolerance); } min = -FastMath.PI; max = FastMath.PI; result = transformer.transform(f, min, max, N, TransformType.INVERSE); Assert.assertEquals(0.0, result[1].getReal(), tolerance); Assert.assertEquals(-0.5, result[1].getImaginary(), tolerance); Assert.assertEquals(0.0, result[N-1].getReal(), tolerance); Assert.assertEquals(0.5, result[N-1].getImaginary(), tolerance); for (int i = 0; i < N-1; i += (i == 0 ? 2 : 1)) { Assert.assertEquals(0.0, result[i].getReal(), tolerance); Assert.assertEquals(0.0, result[i].getImaginary(), tolerance); } } /* * Additional tests for 2D data. */ @Test public void test2DData() { FastFourierTransformer transformer; transformer = new FastFourierTransformer(DftNormalization.STANDARD); double tolerance = 1E-12; Complex[][] input = new Complex[][] {new Complex[] {new Complex(1, 0), new Complex(2, 0)}, new Complex[] {new Complex(3, 1), new Complex(4, 2)}}; Complex[][] goodOutput = new Complex[][] {new Complex[] {new Complex(5, 1.5), new Complex(-1, -.5)}, new Complex[] {new Complex(-2, -1.5), new Complex(0, .5)}}; for (int i = 0; i < goodOutput.length; i++) { TransformUtils.scaleArray( goodOutput[i], FastMath.sqrt(goodOutput[i].length) * FastMath.sqrt(goodOutput.length)); } Complex[][] output = (Complex[][])transformer.mdfft(input, TransformType.FORWARD); Complex[][] output2 = (Complex[][])transformer.mdfft(output, TransformType.INVERSE); Assert.assertEquals(input.length, output.length); Assert.assertEquals(input.length, output2.length); Assert.assertEquals(input[0].length, output[0].length); Assert.assertEquals(input[0].length, output2[0].length); Assert.assertEquals(input[1].length, output[1].length); Assert.assertEquals(input[1].length, output2[1].length); for (int i = 0; i < input.length; i++) { for (int j = 0; j < input[0].length; j++) { Assert.assertEquals(input[i][j].getImaginary(), output2[i][j].getImaginary(), tolerance); Assert.assertEquals(input[i][j].getReal(), output2[i][j].getReal(), tolerance); Assert.assertEquals(goodOutput[i][j].getImaginary(), output[i][j].getImaginary(), tolerance); Assert.assertEquals(goodOutput[i][j].getReal(), output[i][j].getReal(), tolerance); } } } @Test public void test2DDataUnitary() { FastFourierTransformer transformer; transformer = new FastFourierTransformer(DftNormalization.UNITARY); double tolerance = 1E-12; Complex[][] input = new Complex[][] {new Complex[] {new Complex(1, 0), new Complex(2, 0)}, new Complex[] {new Complex(3, 1), new Complex(4, 2)}}; Complex[][] goodOutput = new Complex[][] {new Complex[] {new Complex(5, 1.5), new Complex(-1, -.5)}, new Complex[] {new Complex(-2, -1.5), new Complex(0, .5)}}; Complex[][] output = (Complex[][])transformer.mdfft(input, TransformType.FORWARD); Complex[][] output2 = (Complex[][])transformer.mdfft(output, TransformType.INVERSE); Assert.assertEquals(input.length, output.length); Assert.assertEquals(input.length, output2.length); Assert.assertEquals(input[0].length, output[0].length); Assert.assertEquals(input[0].length, output2[0].length); Assert.assertEquals(input[1].length, output[1].length); Assert.assertEquals(input[1].length, output2[1].length); for (int i = 0; i < input.length; i++) { for (int j = 0; j < input[0].length; j++) { Assert.assertEquals(input[i][j].getImaginary(), output2[i][j].getImaginary(), tolerance); Assert.assertEquals(input[i][j].getReal(), output2[i][j].getReal(), tolerance); Assert.assertEquals(goodOutput[i][j].getImaginary(), output[i][j].getImaginary(), tolerance); Assert.assertEquals(goodOutput[i][j].getReal(), output[i][j].getReal(), tolerance); } } } }
[ { "be_test_class_file": "org/apache/commons/math3/transform/FastFourierTransformer.java", "be_test_class_name": "org.apache.commons.math3.transform.FastFourierTransformer", "be_test_function_name": "bitReversalShuffle2", "be_test_function_signature": "([D[D)V", "line_numbers": [ "130", "131", "132", "134", "135", "136", "138", "139", "140", "142", "143", "144", "147", "148", "149", "150", "152", "154" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/transform/FastFourierTransformer.java", "be_test_class_name": "org.apache.commons.math3.transform.FastFourierTransformer", "be_test_function_name": "normalizeTransformedData", "be_test_function_signature": "([[DLorg/apache/commons/math3/transform/DftNormalization;Lorg/apache/commons/math3/transform/TransformType;)V", "line_numbers": [ "166", "167", "168", "169", "171", "173", "174", "175", "176", "177", "179", "182", "183", "184", "185", "187", "195", "197" ], "method_line_rate": 0.9444444444444444 }, { "be_test_class_file": "org/apache/commons/math3/transform/FastFourierTransformer.java", "be_test_class_name": "org.apache.commons.math3.transform.FastFourierTransformer", "be_test_function_name": "transform", "be_test_function_signature": "([DLorg/apache/commons/math3/transform/TransformType;)[Lorg/apache/commons/math3/complex/Complex;", "line_numbers": [ "371", "375", "377" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/transform/FastFourierTransformer.java", "be_test_class_name": "org.apache.commons.math3.transform.FastFourierTransformer", "be_test_function_name": "transform", "be_test_function_signature": "([Lorg/apache/commons/math3/complex/Complex;Lorg/apache/commons/math3/transform/TransformType;)[Lorg/apache/commons/math3/complex/Complex;", "line_numbers": [ "414", "416", "418" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/transform/FastFourierTransformer.java", "be_test_class_name": "org.apache.commons.math3.transform.FastFourierTransformer", "be_test_function_name": "transformInPlace", "be_test_function_signature": "([[DLorg/apache/commons/math3/transform/DftNormalization;Lorg/apache/commons/math3/transform/TransformType;)V", "line_numbers": [ "218", "219", "221", "222", "223", "224", "227", "228", "229", "234", "235", "236", "237", "238", "239", "240", "243", "244", "246", "247", "249", "250", "253", "256", "257", "258", "259", "260", "262", "263", "264", "265", "266", "267", "268", "269", "273", "274", "276", "277", "279", "280", "282", "283", "286", "287", "288", "289", "291", "292", "293", "294", "295", "296", "297", "298", "302", "303", "305", "306", "308", "309", "311", "312", "316", "317", "318", "319", "320", "321", "322", "323", "324", "328", "329", "331", "332", "334", "335", "336", "337", "338", "341", "342", "344", "345", "348", "349", "350", "351", "355", "356", "357", "359", "360" ], "method_line_rate": 0.8526315789473684 } ]
public class LogAxisTests extends TestCase
public void testAutoRange1() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.setValue(100.0, "Row 1", "Column 1"); dataset.setValue(200.0, "Row 1", "Column 2"); JFreeChart chart = ChartFactory.createBarChart("Test", "Categories", "Value", dataset, false); CategoryPlot plot = (CategoryPlot) chart.getPlot(); LogAxis axis = new LogAxis("Log(Y)"); plot.setRangeAxis(axis); assertEquals(0.0, axis.getLowerBound(), EPSILON); assertEquals(2.6066426411261268E7, axis.getUpperBound(), EPSILON); }
// // Abstract Java Tested Class // 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.text.DecimalFormat; // import java.text.NumberFormat; // import java.util.ArrayList; // import java.util.List; // import java.util.Locale; // 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.LogFormat; // import org.jfree.chart.util.RectangleEdge; // import org.jfree.chart.util.RectangleInsets; // import org.jfree.data.Range; // // // // public class LogAxis extends ValueAxis { // private double base = 10.0; // private double baseLog = Math.log(10.0); // private double smallestValue = 1E-100; // private NumberTickUnit tickUnit; // private NumberFormat numberFormatOverride; // // public LogAxis(); // public LogAxis(String label); // public double getBase(); // public void setBase(double base); // public double getSmallestValue(); // public void setSmallestValue(double value); // public NumberTickUnit getTickUnit(); // public void setTickUnit(NumberTickUnit unit); // public void setTickUnit(NumberTickUnit unit, boolean notify, // boolean turnOffAutoSelect); // public NumberFormat getNumberFormatOverride(); // public void setNumberFormatOverride(NumberFormat formatter); // public double calculateLog(double value); // public double calculateValue(double log); // public double java2DToValue(double java2DValue, Rectangle2D area, // RectangleEdge edge); // public double valueToJava2D(double value, Rectangle2D area, // RectangleEdge edge); // public void configure(); // protected void autoAdjustRange(); // public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, // Rectangle2D dataArea, RectangleEdge edge, // PlotRenderingInfo plotState); // public List refreshTicks(Graphics2D g2, AxisState state, // Rectangle2D dataArea, RectangleEdge edge); // protected List refreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, // RectangleEdge edge); // protected List refreshTicksVertical(Graphics2D g2, Rectangle2D dataArea, // RectangleEdge edge); // protected void selectAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, // RectangleEdge edge); // protected void selectHorizontalAutoTickUnit(Graphics2D g2, // Rectangle2D dataArea, RectangleEdge edge); // public double exponentLengthToJava2D(double length, Rectangle2D area, // RectangleEdge edge); // protected void selectVerticalAutoTickUnit(Graphics2D g2, // Rectangle2D dataArea, // RectangleEdge edge); // protected double estimateMaximumTickLabelHeight(Graphics2D g2); // protected double estimateMaximumTickLabelWidth(Graphics2D g2, // TickUnit unit); // public void zoomRange(double lowerPercent, double upperPercent); // public void pan(double percent); // protected String createTickLabel(double value); // public boolean equals(Object obj); // public int hashCode(); // public static TickUnitSource createLogTickUnits(Locale locale); // } // // // Abstract Java Test Class // package org.jfree.chart.axis.junit; // // import java.awt.geom.Rectangle2D; // 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.chart.ChartFactory; // import org.jfree.chart.JFreeChart; // import org.jfree.chart.axis.LogAxis; // import org.jfree.chart.plot.CategoryPlot; // import org.jfree.chart.plot.PlotOrientation; // import org.jfree.chart.plot.XYPlot; // import org.jfree.chart.util.RectangleEdge; // import org.jfree.data.category.DefaultCategoryDataset; // import org.jfree.data.xy.XYSeries; // import org.jfree.data.xy.XYSeriesCollection; // // // // public class LogAxisTests extends TestCase { // private static final double EPSILON = 0.0000001; // // public static Test suite(); // public LogAxisTests(String name); // public void testCloning(); // public void testEquals(); // public void testHashCode(); // public void testTranslateJava2DToValue(); // public void testSerialization(); // public void testAutoRange1(); // public void testAutoRange3(); // public void testXYAutoRange1(); // public void testXYAutoRange2(); // public void testSetLowerBound(); // public void testTickMarksVisibleDefault(); // } // You are a professional Java test case writer, please create a test case named `testAutoRange1` for the `LogAxis` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * A simple test for the auto-range calculation looking at a * LogAxis used as the range axis for a CategoryPlot. */
tests/org/jfree/chart/axis/junit/LogAxisTests.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.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; 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.LogFormat; import org.jfree.chart.util.RectangleEdge; import org.jfree.chart.util.RectangleInsets; import org.jfree.data.Range;
public LogAxis(); public LogAxis(String label); public double getBase(); public void setBase(double base); public double getSmallestValue(); public void setSmallestValue(double value); public NumberTickUnit getTickUnit(); public void setTickUnit(NumberTickUnit unit); public void setTickUnit(NumberTickUnit unit, boolean notify, boolean turnOffAutoSelect); public NumberFormat getNumberFormatOverride(); public void setNumberFormatOverride(NumberFormat formatter); public double calculateLog(double value); public double calculateValue(double log); public double java2DToValue(double java2DValue, Rectangle2D area, RectangleEdge edge); public double valueToJava2D(double value, Rectangle2D area, RectangleEdge edge); public void configure(); protected void autoAdjustRange(); public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState); public List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); protected List refreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected List refreshTicksVertical(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected void selectAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected void selectHorizontalAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); public double exponentLengthToJava2D(double length, Rectangle2D area, RectangleEdge edge); protected void selectVerticalAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected double estimateMaximumTickLabelHeight(Graphics2D g2); protected double estimateMaximumTickLabelWidth(Graphics2D g2, TickUnit unit); public void zoomRange(double lowerPercent, double upperPercent); public void pan(double percent); protected String createTickLabel(double value); public boolean equals(Object obj); public int hashCode(); public static TickUnitSource createLogTickUnits(Locale locale);
211
testAutoRange1
```java // Abstract Java Tested Class 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.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; 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.LogFormat; import org.jfree.chart.util.RectangleEdge; import org.jfree.chart.util.RectangleInsets; import org.jfree.data.Range; public class LogAxis extends ValueAxis { private double base = 10.0; private double baseLog = Math.log(10.0); private double smallestValue = 1E-100; private NumberTickUnit tickUnit; private NumberFormat numberFormatOverride; public LogAxis(); public LogAxis(String label); public double getBase(); public void setBase(double base); public double getSmallestValue(); public void setSmallestValue(double value); public NumberTickUnit getTickUnit(); public void setTickUnit(NumberTickUnit unit); public void setTickUnit(NumberTickUnit unit, boolean notify, boolean turnOffAutoSelect); public NumberFormat getNumberFormatOverride(); public void setNumberFormatOverride(NumberFormat formatter); public double calculateLog(double value); public double calculateValue(double log); public double java2DToValue(double java2DValue, Rectangle2D area, RectangleEdge edge); public double valueToJava2D(double value, Rectangle2D area, RectangleEdge edge); public void configure(); protected void autoAdjustRange(); public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState); public List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); protected List refreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected List refreshTicksVertical(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected void selectAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected void selectHorizontalAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); public double exponentLengthToJava2D(double length, Rectangle2D area, RectangleEdge edge); protected void selectVerticalAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected double estimateMaximumTickLabelHeight(Graphics2D g2); protected double estimateMaximumTickLabelWidth(Graphics2D g2, TickUnit unit); public void zoomRange(double lowerPercent, double upperPercent); public void pan(double percent); protected String createTickLabel(double value); public boolean equals(Object obj); public int hashCode(); public static TickUnitSource createLogTickUnits(Locale locale); } // Abstract Java Test Class package org.jfree.chart.axis.junit; import java.awt.geom.Rectangle2D; 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.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.LogAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.util.RectangleEdge; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; public class LogAxisTests extends TestCase { private static final double EPSILON = 0.0000001; public static Test suite(); public LogAxisTests(String name); public void testCloning(); public void testEquals(); public void testHashCode(); public void testTranslateJava2DToValue(); public void testSerialization(); public void testAutoRange1(); public void testAutoRange3(); public void testXYAutoRange1(); public void testXYAutoRange2(); public void testSetLowerBound(); public void testTickMarksVisibleDefault(); } ``` You are a professional Java test case writer, please create a test case named `testAutoRange1` for the `LogAxis` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * A simple test for the auto-range calculation looking at a * LogAxis used as the range axis for a CategoryPlot. */
200
// // Abstract Java Tested Class // 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.text.DecimalFormat; // import java.text.NumberFormat; // import java.util.ArrayList; // import java.util.List; // import java.util.Locale; // 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.LogFormat; // import org.jfree.chart.util.RectangleEdge; // import org.jfree.chart.util.RectangleInsets; // import org.jfree.data.Range; // // // // public class LogAxis extends ValueAxis { // private double base = 10.0; // private double baseLog = Math.log(10.0); // private double smallestValue = 1E-100; // private NumberTickUnit tickUnit; // private NumberFormat numberFormatOverride; // // public LogAxis(); // public LogAxis(String label); // public double getBase(); // public void setBase(double base); // public double getSmallestValue(); // public void setSmallestValue(double value); // public NumberTickUnit getTickUnit(); // public void setTickUnit(NumberTickUnit unit); // public void setTickUnit(NumberTickUnit unit, boolean notify, // boolean turnOffAutoSelect); // public NumberFormat getNumberFormatOverride(); // public void setNumberFormatOverride(NumberFormat formatter); // public double calculateLog(double value); // public double calculateValue(double log); // public double java2DToValue(double java2DValue, Rectangle2D area, // RectangleEdge edge); // public double valueToJava2D(double value, Rectangle2D area, // RectangleEdge edge); // public void configure(); // protected void autoAdjustRange(); // public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, // Rectangle2D dataArea, RectangleEdge edge, // PlotRenderingInfo plotState); // public List refreshTicks(Graphics2D g2, AxisState state, // Rectangle2D dataArea, RectangleEdge edge); // protected List refreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, // RectangleEdge edge); // protected List refreshTicksVertical(Graphics2D g2, Rectangle2D dataArea, // RectangleEdge edge); // protected void selectAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, // RectangleEdge edge); // protected void selectHorizontalAutoTickUnit(Graphics2D g2, // Rectangle2D dataArea, RectangleEdge edge); // public double exponentLengthToJava2D(double length, Rectangle2D area, // RectangleEdge edge); // protected void selectVerticalAutoTickUnit(Graphics2D g2, // Rectangle2D dataArea, // RectangleEdge edge); // protected double estimateMaximumTickLabelHeight(Graphics2D g2); // protected double estimateMaximumTickLabelWidth(Graphics2D g2, // TickUnit unit); // public void zoomRange(double lowerPercent, double upperPercent); // public void pan(double percent); // protected String createTickLabel(double value); // public boolean equals(Object obj); // public int hashCode(); // public static TickUnitSource createLogTickUnits(Locale locale); // } // // // Abstract Java Test Class // package org.jfree.chart.axis.junit; // // import java.awt.geom.Rectangle2D; // 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.chart.ChartFactory; // import org.jfree.chart.JFreeChart; // import org.jfree.chart.axis.LogAxis; // import org.jfree.chart.plot.CategoryPlot; // import org.jfree.chart.plot.PlotOrientation; // import org.jfree.chart.plot.XYPlot; // import org.jfree.chart.util.RectangleEdge; // import org.jfree.data.category.DefaultCategoryDataset; // import org.jfree.data.xy.XYSeries; // import org.jfree.data.xy.XYSeriesCollection; // // // // public class LogAxisTests extends TestCase { // private static final double EPSILON = 0.0000001; // // public static Test suite(); // public LogAxisTests(String name); // public void testCloning(); // public void testEquals(); // public void testHashCode(); // public void testTranslateJava2DToValue(); // public void testSerialization(); // public void testAutoRange1(); // public void testAutoRange3(); // public void testXYAutoRange1(); // public void testXYAutoRange2(); // public void testSetLowerBound(); // public void testTickMarksVisibleDefault(); // } // You are a professional Java test case writer, please create a test case named `testAutoRange1` for the `LogAxis` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * A simple test for the auto-range calculation looking at a * LogAxis used as the range axis for a CategoryPlot. */ public void testAutoRange1() {
/** * A simple test for the auto-range calculation looking at a * LogAxis used as the range axis for a CategoryPlot. */
1
org.jfree.chart.axis.LogAxis
tests
```java // Abstract Java Tested Class 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.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; 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.LogFormat; import org.jfree.chart.util.RectangleEdge; import org.jfree.chart.util.RectangleInsets; import org.jfree.data.Range; public class LogAxis extends ValueAxis { private double base = 10.0; private double baseLog = Math.log(10.0); private double smallestValue = 1E-100; private NumberTickUnit tickUnit; private NumberFormat numberFormatOverride; public LogAxis(); public LogAxis(String label); public double getBase(); public void setBase(double base); public double getSmallestValue(); public void setSmallestValue(double value); public NumberTickUnit getTickUnit(); public void setTickUnit(NumberTickUnit unit); public void setTickUnit(NumberTickUnit unit, boolean notify, boolean turnOffAutoSelect); public NumberFormat getNumberFormatOverride(); public void setNumberFormatOverride(NumberFormat formatter); public double calculateLog(double value); public double calculateValue(double log); public double java2DToValue(double java2DValue, Rectangle2D area, RectangleEdge edge); public double valueToJava2D(double value, Rectangle2D area, RectangleEdge edge); public void configure(); protected void autoAdjustRange(); public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState); public List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); protected List refreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected List refreshTicksVertical(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected void selectAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected void selectHorizontalAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); public double exponentLengthToJava2D(double length, Rectangle2D area, RectangleEdge edge); protected void selectVerticalAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected double estimateMaximumTickLabelHeight(Graphics2D g2); protected double estimateMaximumTickLabelWidth(Graphics2D g2, TickUnit unit); public void zoomRange(double lowerPercent, double upperPercent); public void pan(double percent); protected String createTickLabel(double value); public boolean equals(Object obj); public int hashCode(); public static TickUnitSource createLogTickUnits(Locale locale); } // Abstract Java Test Class package org.jfree.chart.axis.junit; import java.awt.geom.Rectangle2D; 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.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.LogAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.util.RectangleEdge; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; public class LogAxisTests extends TestCase { private static final double EPSILON = 0.0000001; public static Test suite(); public LogAxisTests(String name); public void testCloning(); public void testEquals(); public void testHashCode(); public void testTranslateJava2DToValue(); public void testSerialization(); public void testAutoRange1(); public void testAutoRange3(); public void testXYAutoRange1(); public void testXYAutoRange2(); public void testSetLowerBound(); public void testTickMarksVisibleDefault(); } ``` You are a professional Java test case writer, please create a test case named `testAutoRange1` for the `LogAxis` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * A simple test for the auto-range calculation looking at a * LogAxis used as the range axis for a CategoryPlot. */ public void testAutoRange1() { ```
public class LogAxis extends ValueAxis
package org.jfree.chart.axis.junit; import java.awt.geom.Rectangle2D; 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.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.LogAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.util.RectangleEdge; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection;
public static Test suite(); public LogAxisTests(String name); public void testCloning(); public void testEquals(); public void testHashCode(); public void testTranslateJava2DToValue(); public void testSerialization(); public void testAutoRange1(); public void testAutoRange3(); public void testXYAutoRange1(); public void testXYAutoRange2(); public void testSetLowerBound(); public void testTickMarksVisibleDefault();
31e9439cef5bdaf00b651c1ad3303f4caada39587cfda758f80fe21e8a1687ea
[ "org.jfree.chart.axis.junit.LogAxisTests::testAutoRange1" ]
private double base = 10.0; private double baseLog = Math.log(10.0); private double smallestValue = 1E-100; private NumberTickUnit tickUnit; private NumberFormat numberFormatOverride;
public void testAutoRange1()
private static final double EPSILON = 0.0000001;
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.] * * ----------------- * LogAxisTests.java * ----------------- * (C) Copyright 2007, 2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 11-Jul-2007 : Version 1 (DG); * 08-Apr-2008 : Fixed incorrect testEquals() method (DG); * */ package org.jfree.chart.axis.junit; import java.awt.geom.Rectangle2D; 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.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.LogAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.util.RectangleEdge; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; /** * Tests for the {@link LogAxis} class. */ public class LogAxisTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(LogAxisTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public LogAxisTests(String name) { super(name); } /** * Confirm that cloning works. */ public void testCloning() { LogAxis a1 = new LogAxis("Test"); LogAxis a2 = null; try { a2 = (LogAxis) a1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(a1 != a2); assertTrue(a1.getClass() == a2.getClass()); assertTrue(a1.equals(a2)); } /** * Confirm that the equals method can distinguish all the required fields. */ public void testEquals() { LogAxis a1 = new LogAxis("Test"); LogAxis a2 = new LogAxis("Test"); assertTrue(a1.equals(a2)); a1.setBase(2.0); assertFalse(a1.equals(a2)); a2.setBase(2.0); assertTrue(a1.equals(a2)); a1.setSmallestValue(0.1); assertFalse(a1.equals(a2)); a2.setSmallestValue(0.1); assertTrue(a1.equals(a2)); a1.setMinorTickCount(8); assertFalse(a1.equals(a2)); a2.setMinorTickCount(8); assertTrue(a1.equals(a2)); } /** * Two objects that are equal are required to return the same hashCode. */ public void testHashCode() { LogAxis a1 = new LogAxis("Test"); LogAxis a2 = new LogAxis("Test"); assertTrue(a1.equals(a2)); int h1 = a1.hashCode(); int h2 = a2.hashCode(); assertEquals(h1, h2); } private static final double EPSILON = 0.0000001; /** * Test the translation of Java2D values to data values. */ public void testTranslateJava2DToValue() { LogAxis axis = new LogAxis(); 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); assertEquals(94.3874312681693, y1, EPSILON); double y2 = axis.java2DToValue(75.0, dataArea, RectangleEdge.RIGHT); assertEquals(94.3874312681693, y2, EPSILON); double x1 = axis.java2DToValue(75.0, dataArea, RectangleEdge.TOP); assertEquals(55.961246381405, x1, EPSILON); double x2 = axis.java2DToValue(75.0, dataArea, RectangleEdge.BOTTOM); assertEquals(55.961246381405, x2, EPSILON); axis.setInverted(true); double y3 = axis.java2DToValue(75.0, dataArea, RectangleEdge.LEFT); assertEquals(52.9731547179647, y3, EPSILON); double y4 = axis.java2DToValue(75.0, dataArea, RectangleEdge.RIGHT); assertEquals(52.9731547179647, y4, EPSILON); double x3 = axis.java2DToValue(75.0, dataArea, RectangleEdge.TOP); assertEquals(89.3475453695651, x3, EPSILON); double x4 = axis.java2DToValue(75.0, dataArea, RectangleEdge.BOTTOM); assertEquals(89.3475453695651, x4, EPSILON); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { LogAxis a1 = new LogAxis("Test Axis"); LogAxis 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 = (LogAxis) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(a1, a2); } /** * A simple test for the auto-range calculation looking at a * LogAxis used as the range axis for a CategoryPlot. */ public void testAutoRange1() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.setValue(100.0, "Row 1", "Column 1"); dataset.setValue(200.0, "Row 1", "Column 2"); JFreeChart chart = ChartFactory.createBarChart("Test", "Categories", "Value", dataset, false); CategoryPlot plot = (CategoryPlot) chart.getPlot(); LogAxis axis = new LogAxis("Log(Y)"); plot.setRangeAxis(axis); assertEquals(0.0, axis.getLowerBound(), EPSILON); assertEquals(2.6066426411261268E7, axis.getUpperBound(), EPSILON); } /** * A simple test for the auto-range calculation looking at a * NumberAxis used as the range axis for a CategoryPlot. In this * case, the original dataset is replaced with a new dataset. */ public void testAutoRange3() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.setValue(100.0, "Row 1", "Column 1"); dataset.setValue(200.0, "Row 1", "Column 2"); JFreeChart chart = ChartFactory.createLineChart("Test", "Categories", "Value", dataset, false); CategoryPlot plot = (CategoryPlot) chart.getPlot(); LogAxis axis = new LogAxis("Log(Y)"); plot.setRangeAxis(axis); assertEquals(96.59363289248458, axis.getLowerBound(), EPSILON); assertEquals(207.0529847682752, axis.getUpperBound(), EPSILON); // now replacing the dataset should update the axis range... DefaultCategoryDataset dataset2 = new DefaultCategoryDataset(); dataset2.setValue(900.0, "Row 1", "Column 1"); dataset2.setValue(1000.0, "Row 1", "Column 2"); plot.setDataset(dataset2); assertEquals(895.2712433374774, axis.getLowerBound(), EPSILON); assertEquals(1005.2819262292991, axis.getUpperBound(), EPSILON); } /** * Checks that the auto-range for the domain axis on an XYPlot is * working as expected. */ public void testXYAutoRange1() { XYSeries series = new XYSeries("Series 1"); series.add(1.0, 1.0); series.add(2.0, 2.0); series.add(3.0, 3.0); XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(series); JFreeChart chart = ChartFactory.createScatterPlot("Test", "X", "Y", dataset, false); XYPlot plot = (XYPlot) chart.getPlot(); LogAxis axis = new LogAxis("Log(Y)"); plot.setRangeAxis(axis); assertEquals(0.9465508226401592, axis.getLowerBound(), EPSILON); assertEquals(3.1694019256486126, axis.getUpperBound(), EPSILON); } /** * Checks that the auto-range for the range axis on an XYPlot is * working as expected. */ public void testXYAutoRange2() { XYSeries series = new XYSeries("Series 1"); series.add(1.0, 1.0); series.add(2.0, 2.0); series.add(3.0, 3.0); XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(series); JFreeChart chart = ChartFactory.createScatterPlot("Test", "X", "Y", dataset, false); XYPlot plot = (XYPlot) chart.getPlot(); LogAxis axis = new LogAxis("Log(Y)"); plot.setRangeAxis(axis); assertEquals(0.9465508226401592, axis.getLowerBound(), EPSILON); assertEquals(3.1694019256486126, axis.getUpperBound(), EPSILON); } /** * Some checks for the setLowerBound() method. */ public void testSetLowerBound() { LogAxis axis = new LogAxis("X"); axis.setRange(0.0, 10.0); axis.setLowerBound(5.0); assertEquals(5.0, axis.getLowerBound(), EPSILON); axis.setLowerBound(10.0); assertEquals(10.0, axis.getLowerBound(), EPSILON); assertEquals(11.0, axis.getUpperBound(), EPSILON); } /** * Checks the default value for the tickMarksVisible flag. */ public void testTickMarksVisibleDefault() { LogAxis axis = new LogAxis("Log Axis"); assertTrue(axis.isTickMarksVisible()); } }
[ { "be_test_class_file": "org/jfree/chart/axis/LogAxis.java", "be_test_class_name": "org.jfree.chart.axis.LogAxis", "be_test_function_name": "autoAdjustRange", "be_test_function_signature": "()V", "line_numbers": [ "385", "386", "387", "390", "391", "393", "394", "395", "398", "399", "400", "403", "404", "405", "409", "410", "411", "412", "413", "417", "418", "419", "420", "421", "422", "423", "426", "429" ], "method_line_rate": 0.8214285714285714 }, { "be_test_class_file": "org/jfree/chart/axis/LogAxis.java", "be_test_class_name": "org.jfree.chart.axis.LogAxis", "be_test_function_name": "calculateLog", "be_test_function_signature": "(D)D", "line_numbers": [ "275" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/LogAxis.java", "be_test_class_name": "org.jfree.chart.axis.LogAxis", "be_test_function_name": "calculateValue", "be_test_function_signature": "(D)D", "line_numbers": [ "289" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/LogAxis.java", "be_test_class_name": "org.jfree.chart.axis.LogAxis", "be_test_function_name": "configure", "be_test_function_signature": "()V", "line_numbers": [ "375", "376", "378" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/LogAxis.java", "be_test_class_name": "org.jfree.chart.axis.LogAxis", "be_test_function_name": "createLogTickUnits", "be_test_function_signature": "(Ljava/util/Locale;)Lorg/jfree/chart/axis/TickUnitSource;", "line_numbers": [ "913", "914", "915", "916", "917", "918", "919", "920", "921", "922", "923", "924", "925", "926", "927", "928", "929" ], "method_line_rate": 1 } ]
public class TypeCheckTest extends CompilerTypeTestCase
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"); }
// 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 `testBug901455` for the `TypeCheck` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */
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,991
testBug901455
```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 `testBug901455` for the `TypeCheck` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */
6,986
// 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 `testBug901455` for the `TypeCheck` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * 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 {
/** * Tests that undefined can be compared shallowly to a value of type * (number,undefined) regardless of the side on which the undefined * value is. */
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 `testBug901455` for the `TypeCheck` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * 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 { ```
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);
341ed57aae7c9a0b6f9da1a1cebd4cc9384c852b748a6520815972bb0f626ae7
[ "com.google.javascript.jscomp.TypeCheckTest::testBug901455" ]
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 testBug901455() 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.27906976744186046 }, { "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": "visitCall", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "1778", "1779", "1781", "1782", "1783", "1784", "1789", "1790", "1794", "1798", "1803", "1809", "1812", "1813", "1814", "1815", "1821" ], "method_line_rate": 0.6470588235294118 }, { "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": "visitParameterList", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/jstype/FunctionType;)V", "line_numbers": [ "1828", "1829", "1831", "1832", "1833", "1834", "1835", "1840", "1841", "1843", "1844", "1846", "1850", "1851", "1852", "1853", "1854", "1860" ], "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": "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.9411764705882353 } ]
public class MultiBackgroundInitializerTest
@Test(expected = NoSuchElementException.class) public void testResultGetExceptionUnknown() throws ConcurrentException { final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize(); res.getException("unknown"); }
// // 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 `testResultGetExceptionUnknown` for the `MultiBackgroundInitializer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tries to query the exception of an unknown child initializer from the * results object. This should cause an exception. */
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);
226
testResultGetExceptionUnknown
```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 `testResultGetExceptionUnknown` for the `MultiBackgroundInitializer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tries to query the exception of an unknown child initializer from the * results object. This should cause an exception. */
222
// // 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 `testResultGetExceptionUnknown` for the `MultiBackgroundInitializer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * 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 {
/** * Tries to query the exception of an unknown child initializer from the * results object. This should cause an exception. */
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 `testResultGetExceptionUnknown` for the `MultiBackgroundInitializer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * 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 { ```
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;
346b6ee4e7c90bb9d91861d23abd027845062b2df5c686d39d5fdf593b3fd985
[ "org.apache.commons.lang3.concurrent.MultiBackgroundInitializerTest::testResultGetExceptionUnknown" ]
private final Map<String, BackgroundInitializer<?>> childInitializers = new HashMap<String, BackgroundInitializer<?>>();
@Test(expected = NoSuchElementException.class) public void testResultGetExceptionUnknown() 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 DepsFileParserTest extends TestCase
public void testGoodParse() { final String CONTENTS = "/*" + "goog.addDependency('no1', [], []);*//*\n" + "goog.addDependency('no2', [ ], [ ]);\n" + "*/goog.addDependency('yes1', [], []);\n" + "/* blah */goog.addDependency(\"yes2\", [], [])/* blah*/\n" + "goog.addDependency('yes3', ['a','b'], ['c']); // goog.addDependency('no3', [], []);\n" + "// goog.addDependency('no4', [], []);\n" + "goog.addDependency(\"yes4\", [], [ \"a\",'b' , 'c' ]); //no new line at EOF"; List<DependencyInfo> result = parser.parseFile(SRC_PATH, CONTENTS); ImmutableList<DependencyInfo> EXPECTED = ImmutableList.<DependencyInfo>of( new SimpleDependencyInfo("yes1", SRC_PATH, EMPTY, EMPTY), new SimpleDependencyInfo("yes2", SRC_PATH, EMPTY, EMPTY), new SimpleDependencyInfo( "yes3", SRC_PATH, ImmutableList.of("a", "b"), ImmutableList.of("c")), new SimpleDependencyInfo( "yes4", SRC_PATH, EMPTY, ImmutableList.of("a", "b", "c")) ); assertEquals(EXPECTED, result); assertEquals(0, errorManager.getErrorCount()); assertEquals(0, errorManager.getWarningCount()); }
// // Abstract Java Tested Class // package com.google.javascript.jscomp.deps; // // import com.google.common.base.CharMatcher; // import com.google.common.base.Function; // import com.google.common.base.Functions; // import com.google.common.collect.Lists; // import com.google.javascript.jscomp.ErrorManager; // import java.io.FileReader; // import java.io.IOException; // import java.io.Reader; // import java.io.StringReader; // import java.util.List; // import java.util.logging.Level; // import java.util.logging.Logger; // import java.util.regex.Matcher; // import java.util.regex.Pattern; // // // // public class DepsFileParser extends JsFileLineParser { // private static Logger logger = Logger.getLogger(DepsFileParser.class.getName()); // private final Matcher depMatcher = // Pattern.compile("\\s*goog.addDependency\\((.*)\\);?\\s*").matcher(""); // private final Matcher depArgsMatch = // Pattern.compile("\\s*([^,]*), (\\[[^\\]]*\\]), (\\[[^\\]]*\\])\\s*").matcher(""); // private List<DependencyInfo> depInfos; // private final Function<String, String> pathTranslator; // // public DepsFileParser(ErrorManager errorManager); // public DepsFileParser(Function<String, String> pathTranslator, // ErrorManager errorManager); // public List<DependencyInfo> parseFile(String filePath) throws IOException; // public List<DependencyInfo> parseFile(String filePath, String fileContents); // public List<DependencyInfo> parseFileReader(String filePath, Reader reader); // @Override // protected boolean parseLine(String line) throws ParseException; // } // // // Abstract Java Test Class // package com.google.javascript.jscomp.deps; // // import com.google.common.collect.ImmutableList; // import com.google.javascript.jscomp.deps.DependencyInfo; // import com.google.javascript.jscomp.deps.DepsFileParser; // import com.google.javascript.jscomp.ErrorManager; // import com.google.javascript.jscomp.PrintStreamErrorManager; // import junit.framework.TestCase; // import java.util.Collections; // import java.util.List; // // // // public class DepsFileParserTest extends TestCase { // private DepsFileParser parser; // private ErrorManager errorManager; // private static final String SRC_PATH = "/path/1.js"; // private final List<String> EMPTY = Collections.emptyList(); // // @Override // public void setUp(); // public void testGoodParse(); // public void testTooFewArgs(); // public void testTooManyArgs(); // public void testShortcutMode(); // public void testNoShortcutMode(); // } // You are a professional Java test case writer, please create a test case named `testGoodParse` for the `DepsFileParser` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests: * -Parsing of comments, * -Parsing of different styles of quotes, * -Parsing of empty arrays, * -Parsing of non-empty arrays, * -Correct recording of what was parsed. */
test/com/google/javascript/jscomp/deps/DepsFileParserTest.java
package com.google.javascript.jscomp.deps; import com.google.common.base.CharMatcher; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.collect.Lists; import com.google.javascript.jscomp.ErrorManager; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern;
public DepsFileParser(ErrorManager errorManager); public DepsFileParser(Function<String, String> pathTranslator, ErrorManager errorManager); public List<DependencyInfo> parseFile(String filePath) throws IOException; public List<DependencyInfo> parseFile(String filePath, String fileContents); public List<DependencyInfo> parseFileReader(String filePath, Reader reader); @Override protected boolean parseLine(String line) throws ParseException;
79
testGoodParse
```java // Abstract Java Tested Class package com.google.javascript.jscomp.deps; import com.google.common.base.CharMatcher; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.collect.Lists; import com.google.javascript.jscomp.ErrorManager; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; public class DepsFileParser extends JsFileLineParser { private static Logger logger = Logger.getLogger(DepsFileParser.class.getName()); private final Matcher depMatcher = Pattern.compile("\\s*goog.addDependency\\((.*)\\);?\\s*").matcher(""); private final Matcher depArgsMatch = Pattern.compile("\\s*([^,]*), (\\[[^\\]]*\\]), (\\[[^\\]]*\\])\\s*").matcher(""); private List<DependencyInfo> depInfos; private final Function<String, String> pathTranslator; public DepsFileParser(ErrorManager errorManager); public DepsFileParser(Function<String, String> pathTranslator, ErrorManager errorManager); public List<DependencyInfo> parseFile(String filePath) throws IOException; public List<DependencyInfo> parseFile(String filePath, String fileContents); public List<DependencyInfo> parseFileReader(String filePath, Reader reader); @Override protected boolean parseLine(String line) throws ParseException; } // Abstract Java Test Class package com.google.javascript.jscomp.deps; import com.google.common.collect.ImmutableList; import com.google.javascript.jscomp.deps.DependencyInfo; import com.google.javascript.jscomp.deps.DepsFileParser; import com.google.javascript.jscomp.ErrorManager; import com.google.javascript.jscomp.PrintStreamErrorManager; import junit.framework.TestCase; import java.util.Collections; import java.util.List; public class DepsFileParserTest extends TestCase { private DepsFileParser parser; private ErrorManager errorManager; private static final String SRC_PATH = "/path/1.js"; private final List<String> EMPTY = Collections.emptyList(); @Override public void setUp(); public void testGoodParse(); public void testTooFewArgs(); public void testTooManyArgs(); public void testShortcutMode(); public void testNoShortcutMode(); } ``` You are a professional Java test case writer, please create a test case named `testGoodParse` for the `DepsFileParser` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests: * -Parsing of comments, * -Parsing of different styles of quotes, * -Parsing of empty arrays, * -Parsing of non-empty arrays, * -Correct recording of what was parsed. */
56
// // Abstract Java Tested Class // package com.google.javascript.jscomp.deps; // // import com.google.common.base.CharMatcher; // import com.google.common.base.Function; // import com.google.common.base.Functions; // import com.google.common.collect.Lists; // import com.google.javascript.jscomp.ErrorManager; // import java.io.FileReader; // import java.io.IOException; // import java.io.Reader; // import java.io.StringReader; // import java.util.List; // import java.util.logging.Level; // import java.util.logging.Logger; // import java.util.regex.Matcher; // import java.util.regex.Pattern; // // // // public class DepsFileParser extends JsFileLineParser { // private static Logger logger = Logger.getLogger(DepsFileParser.class.getName()); // private final Matcher depMatcher = // Pattern.compile("\\s*goog.addDependency\\((.*)\\);?\\s*").matcher(""); // private final Matcher depArgsMatch = // Pattern.compile("\\s*([^,]*), (\\[[^\\]]*\\]), (\\[[^\\]]*\\])\\s*").matcher(""); // private List<DependencyInfo> depInfos; // private final Function<String, String> pathTranslator; // // public DepsFileParser(ErrorManager errorManager); // public DepsFileParser(Function<String, String> pathTranslator, // ErrorManager errorManager); // public List<DependencyInfo> parseFile(String filePath) throws IOException; // public List<DependencyInfo> parseFile(String filePath, String fileContents); // public List<DependencyInfo> parseFileReader(String filePath, Reader reader); // @Override // protected boolean parseLine(String line) throws ParseException; // } // // // Abstract Java Test Class // package com.google.javascript.jscomp.deps; // // import com.google.common.collect.ImmutableList; // import com.google.javascript.jscomp.deps.DependencyInfo; // import com.google.javascript.jscomp.deps.DepsFileParser; // import com.google.javascript.jscomp.ErrorManager; // import com.google.javascript.jscomp.PrintStreamErrorManager; // import junit.framework.TestCase; // import java.util.Collections; // import java.util.List; // // // // public class DepsFileParserTest extends TestCase { // private DepsFileParser parser; // private ErrorManager errorManager; // private static final String SRC_PATH = "/path/1.js"; // private final List<String> EMPTY = Collections.emptyList(); // // @Override // public void setUp(); // public void testGoodParse(); // public void testTooFewArgs(); // public void testTooManyArgs(); // public void testShortcutMode(); // public void testNoShortcutMode(); // } // You are a professional Java test case writer, please create a test case named `testGoodParse` for the `DepsFileParser` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests: * -Parsing of comments, * -Parsing of different styles of quotes, * -Parsing of empty arrays, * -Parsing of non-empty arrays, * -Correct recording of what was parsed. */ public void testGoodParse() {
/** * Tests: * -Parsing of comments, * -Parsing of different styles of quotes, * -Parsing of empty arrays, * -Parsing of non-empty arrays, * -Correct recording of what was parsed. */
107
com.google.javascript.jscomp.deps.DepsFileParser
test
```java // Abstract Java Tested Class package com.google.javascript.jscomp.deps; import com.google.common.base.CharMatcher; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.collect.Lists; import com.google.javascript.jscomp.ErrorManager; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; public class DepsFileParser extends JsFileLineParser { private static Logger logger = Logger.getLogger(DepsFileParser.class.getName()); private final Matcher depMatcher = Pattern.compile("\\s*goog.addDependency\\((.*)\\);?\\s*").matcher(""); private final Matcher depArgsMatch = Pattern.compile("\\s*([^,]*), (\\[[^\\]]*\\]), (\\[[^\\]]*\\])\\s*").matcher(""); private List<DependencyInfo> depInfos; private final Function<String, String> pathTranslator; public DepsFileParser(ErrorManager errorManager); public DepsFileParser(Function<String, String> pathTranslator, ErrorManager errorManager); public List<DependencyInfo> parseFile(String filePath) throws IOException; public List<DependencyInfo> parseFile(String filePath, String fileContents); public List<DependencyInfo> parseFileReader(String filePath, Reader reader); @Override protected boolean parseLine(String line) throws ParseException; } // Abstract Java Test Class package com.google.javascript.jscomp.deps; import com.google.common.collect.ImmutableList; import com.google.javascript.jscomp.deps.DependencyInfo; import com.google.javascript.jscomp.deps.DepsFileParser; import com.google.javascript.jscomp.ErrorManager; import com.google.javascript.jscomp.PrintStreamErrorManager; import junit.framework.TestCase; import java.util.Collections; import java.util.List; public class DepsFileParserTest extends TestCase { private DepsFileParser parser; private ErrorManager errorManager; private static final String SRC_PATH = "/path/1.js"; private final List<String> EMPTY = Collections.emptyList(); @Override public void setUp(); public void testGoodParse(); public void testTooFewArgs(); public void testTooManyArgs(); public void testShortcutMode(); public void testNoShortcutMode(); } ``` You are a professional Java test case writer, please create a test case named `testGoodParse` for the `DepsFileParser` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests: * -Parsing of comments, * -Parsing of different styles of quotes, * -Parsing of empty arrays, * -Parsing of non-empty arrays, * -Correct recording of what was parsed. */ public void testGoodParse() { ```
public class DepsFileParser extends JsFileLineParser
package com.google.javascript.jscomp.deps; import com.google.common.collect.ImmutableList; import com.google.javascript.jscomp.deps.DependencyInfo; import com.google.javascript.jscomp.deps.DepsFileParser; import com.google.javascript.jscomp.ErrorManager; import com.google.javascript.jscomp.PrintStreamErrorManager; import junit.framework.TestCase; import java.util.Collections; import java.util.List;
@Override public void setUp(); public void testGoodParse(); public void testTooFewArgs(); public void testTooManyArgs(); public void testShortcutMode(); public void testNoShortcutMode();
36c4b95a3ef3ecdc4089df9892dfe9773f935c7fb691db6041477a11b2799246
[ "com.google.javascript.jscomp.deps.DepsFileParserTest::testGoodParse" ]
private static Logger logger = Logger.getLogger(DepsFileParser.class.getName()); private final Matcher depMatcher = Pattern.compile("\\s*goog.addDependency\\((.*)\\);?\\s*").matcher(""); private final Matcher depArgsMatch = Pattern.compile("\\s*([^,]*), (\\[[^\\]]*\\]), (\\[[^\\]]*\\])\\s*").matcher(""); private List<DependencyInfo> depInfos; private final Function<String, String> pathTranslator;
public void testGoodParse()
private DepsFileParser parser; private ErrorManager errorManager; private static final String SRC_PATH = "/path/1.js"; private final List<String> EMPTY = Collections.emptyList();
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.deps; import com.google.common.collect.ImmutableList; import com.google.javascript.jscomp.deps.DependencyInfo; import com.google.javascript.jscomp.deps.DepsFileParser; import com.google.javascript.jscomp.ErrorManager; import com.google.javascript.jscomp.PrintStreamErrorManager; import junit.framework.TestCase; import java.util.Collections; import java.util.List; /** * Tests for {@link DepsFileParser}. * * @author agrieve@google.com (Andrew Grieve) */ public class DepsFileParserTest extends TestCase { private DepsFileParser parser; private ErrorManager errorManager; private static final String SRC_PATH = "/path/1.js"; private final List<String> EMPTY = Collections.emptyList(); @Override public void setUp() { errorManager = new PrintStreamErrorManager(System.err); parser = new DepsFileParser(errorManager); parser.setShortcutMode(true); } /** * Tests: * -Parsing of comments, * -Parsing of different styles of quotes, * -Parsing of empty arrays, * -Parsing of non-empty arrays, * -Correct recording of what was parsed. */ public void testGoodParse() { final String CONTENTS = "/*" + "goog.addDependency('no1', [], []);*//*\n" + "goog.addDependency('no2', [ ], [ ]);\n" + "*/goog.addDependency('yes1', [], []);\n" + "/* blah */goog.addDependency(\"yes2\", [], [])/* blah*/\n" + "goog.addDependency('yes3', ['a','b'], ['c']); // goog.addDependency('no3', [], []);\n" + "// goog.addDependency('no4', [], []);\n" + "goog.addDependency(\"yes4\", [], [ \"a\",'b' , 'c' ]); //no new line at EOF"; List<DependencyInfo> result = parser.parseFile(SRC_PATH, CONTENTS); ImmutableList<DependencyInfo> EXPECTED = ImmutableList.<DependencyInfo>of( new SimpleDependencyInfo("yes1", SRC_PATH, EMPTY, EMPTY), new SimpleDependencyInfo("yes2", SRC_PATH, EMPTY, EMPTY), new SimpleDependencyInfo( "yes3", SRC_PATH, ImmutableList.of("a", "b"), ImmutableList.of("c")), new SimpleDependencyInfo( "yes4", SRC_PATH, EMPTY, ImmutableList.of("a", "b", "c")) ); assertEquals(EXPECTED, result); assertEquals(0, errorManager.getErrorCount()); assertEquals(0, errorManager.getWarningCount()); } public void testTooFewArgs() { parser.parseFile(SRC_PATH, "goog.addDependency('a', []);"); assertEquals(1, errorManager.getErrorCount()); assertEquals(0, errorManager.getWarningCount()); } public void testTooManyArgs() { parser.parseFile(SRC_PATH, "goog.addDependency('a', [], [], []);"); assertEquals(1, errorManager.getErrorCount()); assertEquals(0, errorManager.getWarningCount()); } public void testShortcutMode() { List<DependencyInfo> result = parser.parseFile(SRC_PATH, "goog.addDependency('yes1', [], []); \n" + "foo();\n" + "goog.addDependency('no1', [], []);"); ImmutableList<DependencyInfo> EXPECTED = ImmutableList.<DependencyInfo>of( new SimpleDependencyInfo("yes1", SRC_PATH, EMPTY, EMPTY)); assertEquals(EXPECTED, result); } public void testNoShortcutMode() { parser.setShortcutMode(false); List<DependencyInfo> result = parser.parseFile(SRC_PATH, "goog.addDependency('yes1', [], []); \n" + "foo();\n" + "goog.addDependency('yes2', [], []);"); ImmutableList<DependencyInfo> EXPECTED = ImmutableList.<DependencyInfo>of( new SimpleDependencyInfo("yes1", SRC_PATH, EMPTY, EMPTY), new SimpleDependencyInfo("yes2", SRC_PATH, EMPTY, EMPTY)); assertEquals(EXPECTED, result); } }
[ { "be_test_class_file": "com/google/javascript/jscomp/deps/DepsFileParser.java", "be_test_class_name": "com.google.javascript.jscomp.deps.DepsFileParser", "be_test_function_name": "parseFile", "be_test_function_signature": "(Ljava/lang/String;Ljava/lang/String;)Ljava/util/List;", "line_numbers": [ "109" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/deps/DepsFileParser.java", "be_test_class_name": "com.google.javascript.jscomp.deps.DepsFileParser", "be_test_function_name": "parseFileReader", "be_test_function_signature": "(Ljava/lang/String;Ljava/io/Reader;)Ljava/util/List;", "line_numbers": [ "122", "123", "124", "125" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/deps/DepsFileParser.java", "be_test_class_name": "com.google.javascript.jscomp.deps.DepsFileParser", "be_test_function_name": "parseLine", "be_test_function_signature": "(Ljava/lang/String;)Z", "line_numbers": [ "138", "142", "143", "145", "146", "147", "148", "150", "153", "157", "158", "164", "165", "167", "171" ], "method_line_rate": 0.8666666666666667 } ]
public class SoundexTest extends StringEncoderAbstractTest<Soundex>
@Test public void testUsMappingOWithDiaeresis() { Assert.assertEquals("O000", this.getStringEncoder().encode("o")); if (Character.isLetter('\u00f6')) { // o-umlaut try { // uppercase O-umlaut Assert.assertEquals("\u00d6000", this.getStringEncoder().encode("\u00f6")); Assert.fail("Expected IllegalArgumentException not thrown"); } catch (final IllegalArgumentException e) { // expected } } else { Assert.assertEquals("", this.getStringEncoder().encode("\u00f6")); } }
// // Abstract Java Tested Class // package org.apache.commons.codec.language; // // import org.apache.commons.codec.EncoderException; // import org.apache.commons.codec.StringEncoder; // // // // public class Soundex implements StringEncoder { // public static final String US_ENGLISH_MAPPING_STRING = "0123012#02245501262301#202"; // private static final char[] US_ENGLISH_MAPPING = US_ENGLISH_MAPPING_STRING.toCharArray(); // public static final Soundex US_ENGLISH = new Soundex(); // @Deprecated // private int maxLength = 4; // private final char[] soundexMapping; // // public Soundex(); // public Soundex(final char[] mapping); // public Soundex(final String mapping); // public int difference(final String s1, final String s2) throws EncoderException; // @Override // public Object encode(final Object obj) throws EncoderException; // @Override // public String encode(final String str); // @Deprecated // public int getMaxLength(); // private char[] getSoundexMapping(); // private char map(final char ch); // @Deprecated // public void setMaxLength(final int maxLength); // public String soundex(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 SoundexTest extends StringEncoderAbstractTest<Soundex> { // // // @Override // protected Soundex createStringEncoder(); // @Test // public void testB650() throws EncoderException; // @Test // public void testBadCharacters(); // @Test // public void testDifference() throws EncoderException; // @Test // public void testEncodeBasic(); // @Test // public void testEncodeBatch2(); // @Test // public void testEncodeBatch3(); // @Test // public void testEncodeBatch4(); // @Test // public void testEncodeIgnoreApostrophes() throws EncoderException; // @Test // public void testEncodeIgnoreHyphens() throws EncoderException; // @Test // public void testEncodeIgnoreTrimmable(); // @Test // public void testHWRuleEx1(); // @Test // public void testHWRuleEx2(); // @Test // public void testHWRuleEx3() throws EncoderException; // @Test // public void testMsSqlServer1(); // @Test // public void testMsSqlServer2() throws EncoderException; // @Test // public void testMsSqlServer3(); // @Test // public void testNewInstance(); // @Test // public void testNewInstance2(); // @Test // public void testNewInstance3(); // @Test // public void testSoundexUtilsConstructable(); // @Test // public void testSoundexUtilsNullBehaviour(); // @Test // public void testUsEnglishStatic(); // @Test // public void testUsMappingEWithAcute(); // @Test // public void testUsMappingOWithDiaeresis(); // @Test // public void testWikipediaAmericanSoundex(); // } // You are a professional Java test case writer, please create a test case named `testUsMappingOWithDiaeresis` for the `Soundex` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Fancy characters are not mapped by the default US mapping. * * http://issues.apache.org/bugzilla/show_bug.cgi?id=29080 */
src/test/java/org/apache/commons/codec/language/SoundexTest.java
package org.apache.commons.codec.language; import org.apache.commons.codec.EncoderException; import org.apache.commons.codec.StringEncoder;
public Soundex(); public Soundex(final char[] mapping); public Soundex(final String mapping); public int difference(final String s1, final String s2) throws EncoderException; @Override public Object encode(final Object obj) throws EncoderException; @Override public String encode(final String str); @Deprecated public int getMaxLength(); private char[] getSoundexMapping(); private char map(final char ch); @Deprecated public void setMaxLength(final int maxLength); public String soundex(String str);
391
testUsMappingOWithDiaeresis
```java // Abstract Java Tested Class package org.apache.commons.codec.language; import org.apache.commons.codec.EncoderException; import org.apache.commons.codec.StringEncoder; public class Soundex implements StringEncoder { public static final String US_ENGLISH_MAPPING_STRING = "0123012#02245501262301#202"; private static final char[] US_ENGLISH_MAPPING = US_ENGLISH_MAPPING_STRING.toCharArray(); public static final Soundex US_ENGLISH = new Soundex(); @Deprecated private int maxLength = 4; private final char[] soundexMapping; public Soundex(); public Soundex(final char[] mapping); public Soundex(final String mapping); public int difference(final String s1, final String s2) throws EncoderException; @Override public Object encode(final Object obj) throws EncoderException; @Override public String encode(final String str); @Deprecated public int getMaxLength(); private char[] getSoundexMapping(); private char map(final char ch); @Deprecated public void setMaxLength(final int maxLength); public String soundex(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 SoundexTest extends StringEncoderAbstractTest<Soundex> { @Override protected Soundex createStringEncoder(); @Test public void testB650() throws EncoderException; @Test public void testBadCharacters(); @Test public void testDifference() throws EncoderException; @Test public void testEncodeBasic(); @Test public void testEncodeBatch2(); @Test public void testEncodeBatch3(); @Test public void testEncodeBatch4(); @Test public void testEncodeIgnoreApostrophes() throws EncoderException; @Test public void testEncodeIgnoreHyphens() throws EncoderException; @Test public void testEncodeIgnoreTrimmable(); @Test public void testHWRuleEx1(); @Test public void testHWRuleEx2(); @Test public void testHWRuleEx3() throws EncoderException; @Test public void testMsSqlServer1(); @Test public void testMsSqlServer2() throws EncoderException; @Test public void testMsSqlServer3(); @Test public void testNewInstance(); @Test public void testNewInstance2(); @Test public void testNewInstance3(); @Test public void testSoundexUtilsConstructable(); @Test public void testSoundexUtilsNullBehaviour(); @Test public void testUsEnglishStatic(); @Test public void testUsMappingEWithAcute(); @Test public void testUsMappingOWithDiaeresis(); @Test public void testWikipediaAmericanSoundex(); } ``` You are a professional Java test case writer, please create a test case named `testUsMappingOWithDiaeresis` for the `Soundex` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Fancy characters are not mapped by the default US mapping. * * http://issues.apache.org/bugzilla/show_bug.cgi?id=29080 */
377
// // Abstract Java Tested Class // package org.apache.commons.codec.language; // // import org.apache.commons.codec.EncoderException; // import org.apache.commons.codec.StringEncoder; // // // // public class Soundex implements StringEncoder { // public static final String US_ENGLISH_MAPPING_STRING = "0123012#02245501262301#202"; // private static final char[] US_ENGLISH_MAPPING = US_ENGLISH_MAPPING_STRING.toCharArray(); // public static final Soundex US_ENGLISH = new Soundex(); // @Deprecated // private int maxLength = 4; // private final char[] soundexMapping; // // public Soundex(); // public Soundex(final char[] mapping); // public Soundex(final String mapping); // public int difference(final String s1, final String s2) throws EncoderException; // @Override // public Object encode(final Object obj) throws EncoderException; // @Override // public String encode(final String str); // @Deprecated // public int getMaxLength(); // private char[] getSoundexMapping(); // private char map(final char ch); // @Deprecated // public void setMaxLength(final int maxLength); // public String soundex(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 SoundexTest extends StringEncoderAbstractTest<Soundex> { // // // @Override // protected Soundex createStringEncoder(); // @Test // public void testB650() throws EncoderException; // @Test // public void testBadCharacters(); // @Test // public void testDifference() throws EncoderException; // @Test // public void testEncodeBasic(); // @Test // public void testEncodeBatch2(); // @Test // public void testEncodeBatch3(); // @Test // public void testEncodeBatch4(); // @Test // public void testEncodeIgnoreApostrophes() throws EncoderException; // @Test // public void testEncodeIgnoreHyphens() throws EncoderException; // @Test // public void testEncodeIgnoreTrimmable(); // @Test // public void testHWRuleEx1(); // @Test // public void testHWRuleEx2(); // @Test // public void testHWRuleEx3() throws EncoderException; // @Test // public void testMsSqlServer1(); // @Test // public void testMsSqlServer2() throws EncoderException; // @Test // public void testMsSqlServer3(); // @Test // public void testNewInstance(); // @Test // public void testNewInstance2(); // @Test // public void testNewInstance3(); // @Test // public void testSoundexUtilsConstructable(); // @Test // public void testSoundexUtilsNullBehaviour(); // @Test // public void testUsEnglishStatic(); // @Test // public void testUsMappingEWithAcute(); // @Test // public void testUsMappingOWithDiaeresis(); // @Test // public void testWikipediaAmericanSoundex(); // } // You are a professional Java test case writer, please create a test case named `testUsMappingOWithDiaeresis` for the `Soundex` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Fancy characters are not mapped by the default US mapping. * * http://issues.apache.org/bugzilla/show_bug.cgi?id=29080 */ @Test public void testUsMappingOWithDiaeresis() {
/** * Fancy characters are not mapped by the default US mapping. * * http://issues.apache.org/bugzilla/show_bug.cgi?id=29080 */
18
org.apache.commons.codec.language.Soundex
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.codec.language; import org.apache.commons.codec.EncoderException; import org.apache.commons.codec.StringEncoder; public class Soundex implements StringEncoder { public static final String US_ENGLISH_MAPPING_STRING = "0123012#02245501262301#202"; private static final char[] US_ENGLISH_MAPPING = US_ENGLISH_MAPPING_STRING.toCharArray(); public static final Soundex US_ENGLISH = new Soundex(); @Deprecated private int maxLength = 4; private final char[] soundexMapping; public Soundex(); public Soundex(final char[] mapping); public Soundex(final String mapping); public int difference(final String s1, final String s2) throws EncoderException; @Override public Object encode(final Object obj) throws EncoderException; @Override public String encode(final String str); @Deprecated public int getMaxLength(); private char[] getSoundexMapping(); private char map(final char ch); @Deprecated public void setMaxLength(final int maxLength); public String soundex(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 SoundexTest extends StringEncoderAbstractTest<Soundex> { @Override protected Soundex createStringEncoder(); @Test public void testB650() throws EncoderException; @Test public void testBadCharacters(); @Test public void testDifference() throws EncoderException; @Test public void testEncodeBasic(); @Test public void testEncodeBatch2(); @Test public void testEncodeBatch3(); @Test public void testEncodeBatch4(); @Test public void testEncodeIgnoreApostrophes() throws EncoderException; @Test public void testEncodeIgnoreHyphens() throws EncoderException; @Test public void testEncodeIgnoreTrimmable(); @Test public void testHWRuleEx1(); @Test public void testHWRuleEx2(); @Test public void testHWRuleEx3() throws EncoderException; @Test public void testMsSqlServer1(); @Test public void testMsSqlServer2() throws EncoderException; @Test public void testMsSqlServer3(); @Test public void testNewInstance(); @Test public void testNewInstance2(); @Test public void testNewInstance3(); @Test public void testSoundexUtilsConstructable(); @Test public void testSoundexUtilsNullBehaviour(); @Test public void testUsEnglishStatic(); @Test public void testUsMappingEWithAcute(); @Test public void testUsMappingOWithDiaeresis(); @Test public void testWikipediaAmericanSoundex(); } ``` You are a professional Java test case writer, please create a test case named `testUsMappingOWithDiaeresis` for the `Soundex` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Fancy characters are not mapped by the default US mapping. * * http://issues.apache.org/bugzilla/show_bug.cgi?id=29080 */ @Test public void testUsMappingOWithDiaeresis() { ```
public class Soundex 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;
@Override protected Soundex createStringEncoder(); @Test public void testB650() throws EncoderException; @Test public void testBadCharacters(); @Test public void testDifference() throws EncoderException; @Test public void testEncodeBasic(); @Test public void testEncodeBatch2(); @Test public void testEncodeBatch3(); @Test public void testEncodeBatch4(); @Test public void testEncodeIgnoreApostrophes() throws EncoderException; @Test public void testEncodeIgnoreHyphens() throws EncoderException; @Test public void testEncodeIgnoreTrimmable(); @Test public void testHWRuleEx1(); @Test public void testHWRuleEx2(); @Test public void testHWRuleEx3() throws EncoderException; @Test public void testMsSqlServer1(); @Test public void testMsSqlServer2() throws EncoderException; @Test public void testMsSqlServer3(); @Test public void testNewInstance(); @Test public void testNewInstance2(); @Test public void testNewInstance3(); @Test public void testSoundexUtilsConstructable(); @Test public void testSoundexUtilsNullBehaviour(); @Test public void testUsEnglishStatic(); @Test public void testUsMappingEWithAcute(); @Test public void testUsMappingOWithDiaeresis(); @Test public void testWikipediaAmericanSoundex();
382a60fdf3637716d7ed295fa0c01dde7c322745b32ac5aae3c3352fed29d11d
[ "org.apache.commons.codec.language.SoundexTest::testUsMappingOWithDiaeresis" ]
public static final String US_ENGLISH_MAPPING_STRING = "0123012#02245501262301#202"; private static final char[] US_ENGLISH_MAPPING = US_ENGLISH_MAPPING_STRING.toCharArray(); public static final Soundex US_ENGLISH = new Soundex(); @Deprecated private int maxLength = 4; private final char[] soundexMapping;
@Test public void testUsMappingOWithDiaeresis()
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. */ // (FYI: Formatted and sorted with Eclipse) 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 Soundex}. * * <p>Keep this file in UTF-8 encoding for proper Javadoc processing.</p> * * @version $Id$ */ public class SoundexTest extends StringEncoderAbstractTest<Soundex> { @Override protected Soundex createStringEncoder() { return new Soundex(); } @Test public void testB650() throws EncoderException { this.checkEncodingVariations("B650", new String[]{ "BARHAM", "BARONE", "BARRON", "BERNA", "BIRNEY", "BIRNIE", "BOOROM", "BOREN", "BORN", "BOURN", "BOURNE", "BOWRON", "BRAIN", "BRAME", "BRANN", "BRAUN", "BREEN", "BRIEN", "BRIM", "BRIMM", "BRINN", "BRION", "BROOM", "BROOME", "BROWN", "BROWNE", "BRUEN", "BRUHN", "BRUIN", "BRUMM", "BRUN", "BRUNO", "BRYAN", "BURIAN", "BURN", "BURNEY", "BYRAM", "BYRNE", "BYRON", "BYRUM"}); } @Test public void testBadCharacters() { Assert.assertEquals("H452", this.getStringEncoder().encode("HOL>MES")); } @Test public void testDifference() throws EncoderException { // Edge cases Assert.assertEquals(0, this.getStringEncoder().difference(null, null)); Assert.assertEquals(0, this.getStringEncoder().difference("", "")); Assert.assertEquals(0, this.getStringEncoder().difference(" ", " ")); // Normal cases Assert.assertEquals(4, this.getStringEncoder().difference("Smith", "Smythe")); Assert.assertEquals(2, this.getStringEncoder().difference("Ann", "Andrew")); Assert.assertEquals(1, this.getStringEncoder().difference("Margaret", "Andrew")); Assert.assertEquals(0, this.getStringEncoder().difference("Janet", "Margaret")); // Examples from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_de-dz_8co5.asp Assert.assertEquals(4, this.getStringEncoder().difference("Green", "Greene")); Assert.assertEquals(0, this.getStringEncoder().difference("Blotchet-Halls", "Greene")); // Examples from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_setu-sus_3o6w.asp Assert.assertEquals(4, this.getStringEncoder().difference("Smith", "Smythe")); Assert.assertEquals(4, this.getStringEncoder().difference("Smithers", "Smythers")); Assert.assertEquals(2, this.getStringEncoder().difference("Anothers", "Brothers")); } @Test public void testEncodeBasic() { Assert.assertEquals("T235", this.getStringEncoder().encode("testing")); Assert.assertEquals("T000", this.getStringEncoder().encode("The")); Assert.assertEquals("Q200", this.getStringEncoder().encode("quick")); Assert.assertEquals("B650", this.getStringEncoder().encode("brown")); Assert.assertEquals("F200", this.getStringEncoder().encode("fox")); Assert.assertEquals("J513", this.getStringEncoder().encode("jumped")); Assert.assertEquals("O160", this.getStringEncoder().encode("over")); Assert.assertEquals("T000", this.getStringEncoder().encode("the")); Assert.assertEquals("L200", this.getStringEncoder().encode("lazy")); Assert.assertEquals("D200", this.getStringEncoder().encode("dogs")); } /** * Examples from http://www.bradandkathy.com/genealogy/overviewofsoundex.html */ @Test public void testEncodeBatch2() { Assert.assertEquals("A462", this.getStringEncoder().encode("Allricht")); Assert.assertEquals("E166", this.getStringEncoder().encode("Eberhard")); Assert.assertEquals("E521", this.getStringEncoder().encode("Engebrethson")); Assert.assertEquals("H512", this.getStringEncoder().encode("Heimbach")); Assert.assertEquals("H524", this.getStringEncoder().encode("Hanselmann")); Assert.assertEquals("H431", this.getStringEncoder().encode("Hildebrand")); Assert.assertEquals("K152", this.getStringEncoder().encode("Kavanagh")); Assert.assertEquals("L530", this.getStringEncoder().encode("Lind")); Assert.assertEquals("L222", this.getStringEncoder().encode("Lukaschowsky")); Assert.assertEquals("M235", this.getStringEncoder().encode("McDonnell")); Assert.assertEquals("M200", this.getStringEncoder().encode("McGee")); Assert.assertEquals("O155", this.getStringEncoder().encode("Opnian")); Assert.assertEquals("O155", this.getStringEncoder().encode("Oppenheimer")); Assert.assertEquals("R355", this.getStringEncoder().encode("Riedemanas")); Assert.assertEquals("Z300", this.getStringEncoder().encode("Zita")); Assert.assertEquals("Z325", this.getStringEncoder().encode("Zitzmeinn")); } /** * Examples from http://www.archives.gov/research_room/genealogy/census/soundex.html */ @Test public void testEncodeBatch3() { Assert.assertEquals("W252", this.getStringEncoder().encode("Washington")); Assert.assertEquals("L000", this.getStringEncoder().encode("Lee")); Assert.assertEquals("G362", this.getStringEncoder().encode("Gutierrez")); Assert.assertEquals("P236", this.getStringEncoder().encode("Pfister")); Assert.assertEquals("J250", this.getStringEncoder().encode("Jackson")); Assert.assertEquals("T522", this.getStringEncoder().encode("Tymczak")); // For VanDeusen: D-250 (D, 2 for the S, 5 for the N, 0 added) is also // possible. Assert.assertEquals("V532", this.getStringEncoder().encode("VanDeusen")); } /** * Examples from: http://www.myatt.demon.co.uk/sxalg.htm */ @Test public void testEncodeBatch4() { Assert.assertEquals("H452", this.getStringEncoder().encode("HOLMES")); Assert.assertEquals("A355", this.getStringEncoder().encode("ADOMOMI")); Assert.assertEquals("V536", this.getStringEncoder().encode("VONDERLEHR")); Assert.assertEquals("B400", this.getStringEncoder().encode("BALL")); Assert.assertEquals("S000", this.getStringEncoder().encode("SHAW")); Assert.assertEquals("J250", this.getStringEncoder().encode("JACKSON")); Assert.assertEquals("S545", this.getStringEncoder().encode("SCANLON")); Assert.assertEquals("S532", this.getStringEncoder().encode("SAINTJOHN")); } @Test public void testEncodeIgnoreApostrophes() throws EncoderException { this.checkEncodingVariations("O165", new String[]{ "OBrien", "'OBrien", "O'Brien", "OB'rien", "OBr'ien", "OBri'en", "OBrie'n", "OBrien'"}); } /** * Test data from http://www.myatt.demon.co.uk/sxalg.htm * * @throws EncoderException */ @Test public void testEncodeIgnoreHyphens() throws EncoderException { this.checkEncodingVariations("K525", new String[]{ "KINGSMITH", "-KINGSMITH", "K-INGSMITH", "KI-NGSMITH", "KIN-GSMITH", "KING-SMITH", "KINGS-MITH", "KINGSM-ITH", "KINGSMI-TH", "KINGSMIT-H", "KINGSMITH-"}); } @Test public void testEncodeIgnoreTrimmable() { Assert.assertEquals("W252", this.getStringEncoder().encode(" \t\n\r Washington \t\n\r ")); } /** * Consonants from the same code group separated by W or H are treated as one. */ @Test public void testHWRuleEx1() { // From // http://www.archives.gov/research_room/genealogy/census/soundex.html: // Ashcraft is coded A-261 (A, 2 for the S, C ignored, 6 for the R, 1 // for the F). It is not coded A-226. Assert.assertEquals("A261", this.getStringEncoder().encode("Ashcraft")); Assert.assertEquals("A261", this.getStringEncoder().encode("Ashcroft")); Assert.assertEquals("Y330", this.getStringEncoder().encode("yehudit")); Assert.assertEquals("Y330", this.getStringEncoder().encode("yhwdyt")); } /** * Consonants from the same code group separated by W or H are treated as one. * * Test data from http://www.myatt.demon.co.uk/sxalg.htm */ @Test public void testHWRuleEx2() { Assert.assertEquals("B312", this.getStringEncoder().encode("BOOTHDAVIS")); Assert.assertEquals("B312", this.getStringEncoder().encode("BOOTH-DAVIS")); } /** * Consonants from the same code group separated by W or H are treated as one. * * @throws EncoderException */ @Test public void testHWRuleEx3() throws EncoderException { Assert.assertEquals("S460", this.getStringEncoder().encode("Sgler")); Assert.assertEquals("S460", this.getStringEncoder().encode("Swhgler")); // Also S460: this.checkEncodingVariations("S460", new String[]{ "SAILOR", "SALYER", "SAYLOR", "SCHALLER", "SCHELLER", "SCHILLER", "SCHOOLER", "SCHULER", "SCHUYLER", "SEILER", "SEYLER", "SHOLAR", "SHULER", "SILAR", "SILER", "SILLER"}); } /** * Examples for MS SQLServer from * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_setu-sus_3o6w.asp */ @Test public void testMsSqlServer1() { Assert.assertEquals("S530", this.getStringEncoder().encode("Smith")); Assert.assertEquals("S530", this.getStringEncoder().encode("Smythe")); } /** * Examples for MS SQLServer from * http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support * /kb/articles/Q100/3/65.asp&NoWebContent=1 * * @throws EncoderException */ @Test public void testMsSqlServer2() throws EncoderException { this.checkEncodingVariations("E625", new String[]{"Erickson", "Erickson", "Erikson", "Ericson", "Ericksen", "Ericsen"}); } /** * Examples for MS SQLServer from http://databases.about.com/library/weekly/aa042901a.htm */ @Test public void testMsSqlServer3() { Assert.assertEquals("A500", this.getStringEncoder().encode("Ann")); Assert.assertEquals("A536", this.getStringEncoder().encode("Andrew")); Assert.assertEquals("J530", this.getStringEncoder().encode("Janet")); Assert.assertEquals("M626", this.getStringEncoder().encode("Margaret")); Assert.assertEquals("S315", this.getStringEncoder().encode("Steven")); Assert.assertEquals("M240", this.getStringEncoder().encode("Michael")); Assert.assertEquals("R163", this.getStringEncoder().encode("Robert")); Assert.assertEquals("L600", this.getStringEncoder().encode("Laura")); Assert.assertEquals("A500", this.getStringEncoder().encode("Anne")); } /** * https://issues.apache.org/jira/browse/CODEC-54 https://issues.apache.org/jira/browse/CODEC-56 */ @Test public void testNewInstance() { Assert.assertEquals("W452", new Soundex().soundex("Williams")); } @Test public void testNewInstance2() { Assert.assertEquals("W452", new Soundex(Soundex.US_ENGLISH_MAPPING_STRING.toCharArray()).soundex("Williams")); } @Test public void testNewInstance3() { Assert.assertEquals("W452", new Soundex(Soundex.US_ENGLISH_MAPPING_STRING).soundex("Williams")); } @Test public void testSoundexUtilsConstructable() { new SoundexUtils(); } @Test public void testSoundexUtilsNullBehaviour() { Assert.assertEquals(null, SoundexUtils.clean(null)); Assert.assertEquals("", SoundexUtils.clean("")); Assert.assertEquals(0, SoundexUtils.differenceEncoded(null, "")); Assert.assertEquals(0, SoundexUtils.differenceEncoded("", null)); } /** * https://issues.apache.org/jira/browse/CODEC-54 https://issues.apache.org/jira/browse/CODEC-56 */ @Test public void testUsEnglishStatic() { Assert.assertEquals("W452", Soundex.US_ENGLISH.soundex("Williams")); } /** * Fancy characters are not mapped by the default US mapping. * * http://issues.apache.org/bugzilla/show_bug.cgi?id=29080 */ @Test public void testUsMappingEWithAcute() { Assert.assertEquals("E000", this.getStringEncoder().encode("e")); if (Character.isLetter('\u00e9')) { // e-acute try { // uppercase E-acute Assert.assertEquals("\u00c9000", this.getStringEncoder().encode("\u00e9")); Assert.fail("Expected IllegalArgumentException not thrown"); } catch (final IllegalArgumentException e) { // expected } } else { Assert.assertEquals("", this.getStringEncoder().encode("\u00e9")); } } /** * Fancy characters are not mapped by the default US mapping. * * http://issues.apache.org/bugzilla/show_bug.cgi?id=29080 */ @Test public void testUsMappingOWithDiaeresis() { Assert.assertEquals("O000", this.getStringEncoder().encode("o")); if (Character.isLetter('\u00f6')) { // o-umlaut try { // uppercase O-umlaut Assert.assertEquals("\u00d6000", this.getStringEncoder().encode("\u00f6")); Assert.fail("Expected IllegalArgumentException not thrown"); } catch (final IllegalArgumentException e) { // expected } } else { Assert.assertEquals("", this.getStringEncoder().encode("\u00f6")); } } /** * Tests example from http://en.wikipedia.org/wiki/Soundex#American_Soundex as of 2015-03-22. */ @Test public void testWikipediaAmericanSoundex() { Assert.assertEquals("R163", this.getStringEncoder().encode("Robert")); Assert.assertEquals("R163", this.getStringEncoder().encode("Rupert")); Assert.assertEquals("A261", this.getStringEncoder().encode("Ashcraft")); Assert.assertEquals("A261", this.getStringEncoder().encode("Ashcroft")); Assert.assertEquals("T522", this.getStringEncoder().encode("Tymczak")); Assert.assertEquals("P236", this.getStringEncoder().encode("Pfister")); } }
[ { "be_test_class_file": "org/apache/commons/codec/language/Soundex.java", "be_test_class_name": "org.apache.commons.codec.language.Soundex", "be_test_function_name": "encode", "be_test_function_signature": "(Ljava/lang/String;)Ljava/lang/String;", "line_numbers": [ "167" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/codec/language/Soundex.java", "be_test_class_name": "org.apache.commons.codec.language.Soundex", "be_test_function_name": "getSoundexMapping", "be_test_function_signature": "()[C", "line_numbers": [ "187" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/codec/language/Soundex.java", "be_test_class_name": "org.apache.commons.codec.language.Soundex", "be_test_function_name": "map", "be_test_function_signature": "(C)C", "line_numbers": [ "200", "201", "202", "204" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/codec/language/Soundex.java", "be_test_class_name": "org.apache.commons.codec.language.Soundex", "be_test_function_name": "soundex", "be_test_function_signature": "(Ljava/lang/String;)Ljava/lang/String;", "line_numbers": [ "229", "230", "232", "233", "234", "236", "238", "239", "241", "242", "243", "244", "245", "246", "247", "248", "251" ], "method_line_rate": 0.5294117647058824 } ]
public final class MicrosphereInterpolatorTest
@Test public void testParaboloid2D() { MultivariateFunction f = new MultivariateFunction() { public double value(double[] x) { if (x.length != 2) { throw new IllegalArgumentException(); } return 2 * x[0] * x[0] - 3 * x[1] * x[1] + 4 * x[0] * x[1] - 5; } }; MultivariateInterpolator interpolator = new MicrosphereInterpolator(); // Interpolating points in [-10, 10][-10, 10] by steps of 2. final int n = 121; final int dim = 2; double[][] x = new double[n][dim]; double[] y = new double[n]; int index = 0; for (int i = -10; i <= 10; i += 2) { for (int j = -10; j <= 10; j += 2) { x[index][0] = i; x[index][1] = j; y[index] = f.value(x[index]); ++index; } } MultivariateFunction p = interpolator.interpolate(x, y); double[] c = new double[dim]; double expected, result; c[0] = 0; c[1] = 0; expected = f.value(c); result = p.value(c); Assert.assertEquals("On sample point", expected, result, FastMath.ulp(1d)); c[0] = 2 + 1e-5; c[1] = 2 - 1e-5; expected = f.value(c); result = p.value(c); Assert.assertEquals("1e-5 away from sample point", expected, result, 1e-3); }
// // Abstract Java Tested Class // package org.apache.commons.math3.analysis.interpolation; // // import org.apache.commons.math3.analysis.MultivariateFunction; // import org.apache.commons.math3.exception.NotPositiveException; // import org.apache.commons.math3.exception.NotStrictlyPositiveException; // import org.apache.commons.math3.exception.NoDataException; // import org.apache.commons.math3.exception.DimensionMismatchException; // import org.apache.commons.math3.exception.NullArgumentException; // import org.apache.commons.math3.random.UnitSphereRandomVectorGenerator; // // // // public class MicrosphereInterpolator // implements MultivariateInterpolator { // public static final int DEFAULT_MICROSPHERE_ELEMENTS = 2000; // public static final int DEFAULT_BRIGHTNESS_EXPONENT = 2; // private final int microsphereElements; // private final int brightnessExponent; // // public MicrosphereInterpolator(); // public MicrosphereInterpolator(final int elements, // final int exponent) // throws NotPositiveException, // NotStrictlyPositiveException; // public MultivariateFunction interpolate(final double[][] xval, // final double[] yval) // throws DimensionMismatchException, // NoDataException, // NullArgumentException; // } // // // Abstract Java Test Class // package org.apache.commons.math3.analysis.interpolation; // // import org.apache.commons.math3.analysis.MultivariateFunction; // import org.apache.commons.math3.util.FastMath; // import org.junit.Assert; // import org.junit.Test; // // // // public final class MicrosphereInterpolatorTest { // // // @Test // public void testLinearFunction2D(); // @Test // public void testParaboloid2D(); // public double value(double[] x); // public double value(double[] x); // } // You are a professional Java test case writer, please create a test case named `testParaboloid2D` for the `MicrosphereInterpolator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test of interpolator for a quadratic function. * <p> * y = 2 x<sub>1</sub><sup>2</sup> - 3 x<sub>2</sub><sup>2</sup> * + 4 x<sub>1</sub> x<sub>2</sub> - 5 */
src/test/java/org/apache/commons/math3/analysis/interpolation/MicrosphereInterpolatorTest.java
package org.apache.commons.math3.analysis.interpolation; import org.apache.commons.math3.analysis.MultivariateFunction; import org.apache.commons.math3.exception.NotPositiveException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.NoDataException; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.random.UnitSphereRandomVectorGenerator;
public MicrosphereInterpolator(); public MicrosphereInterpolator(final int elements, final int exponent) throws NotPositiveException, NotStrictlyPositiveException; public MultivariateFunction interpolate(final double[][] xval, final double[] yval) throws DimensionMismatchException, NoDataException, NullArgumentException;
130
testParaboloid2D
```java // Abstract Java Tested Class package org.apache.commons.math3.analysis.interpolation; import org.apache.commons.math3.analysis.MultivariateFunction; import org.apache.commons.math3.exception.NotPositiveException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.NoDataException; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.random.UnitSphereRandomVectorGenerator; public class MicrosphereInterpolator implements MultivariateInterpolator { public static final int DEFAULT_MICROSPHERE_ELEMENTS = 2000; public static final int DEFAULT_BRIGHTNESS_EXPONENT = 2; private final int microsphereElements; private final int brightnessExponent; public MicrosphereInterpolator(); public MicrosphereInterpolator(final int elements, final int exponent) throws NotPositiveException, NotStrictlyPositiveException; public MultivariateFunction interpolate(final double[][] xval, final double[] yval) throws DimensionMismatchException, NoDataException, NullArgumentException; } // Abstract Java Test Class package org.apache.commons.math3.analysis.interpolation; import org.apache.commons.math3.analysis.MultivariateFunction; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; public final class MicrosphereInterpolatorTest { @Test public void testLinearFunction2D(); @Test public void testParaboloid2D(); public double value(double[] x); public double value(double[] x); } ``` You are a professional Java test case writer, please create a test case named `testParaboloid2D` for the `MicrosphereInterpolator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test of interpolator for a quadratic function. * <p> * y = 2 x<sub>1</sub><sup>2</sup> - 3 x<sub>2</sub><sup>2</sup> * + 4 x<sub>1</sub> x<sub>2</sub> - 5 */
86
// // Abstract Java Tested Class // package org.apache.commons.math3.analysis.interpolation; // // import org.apache.commons.math3.analysis.MultivariateFunction; // import org.apache.commons.math3.exception.NotPositiveException; // import org.apache.commons.math3.exception.NotStrictlyPositiveException; // import org.apache.commons.math3.exception.NoDataException; // import org.apache.commons.math3.exception.DimensionMismatchException; // import org.apache.commons.math3.exception.NullArgumentException; // import org.apache.commons.math3.random.UnitSphereRandomVectorGenerator; // // // // public class MicrosphereInterpolator // implements MultivariateInterpolator { // public static final int DEFAULT_MICROSPHERE_ELEMENTS = 2000; // public static final int DEFAULT_BRIGHTNESS_EXPONENT = 2; // private final int microsphereElements; // private final int brightnessExponent; // // public MicrosphereInterpolator(); // public MicrosphereInterpolator(final int elements, // final int exponent) // throws NotPositiveException, // NotStrictlyPositiveException; // public MultivariateFunction interpolate(final double[][] xval, // final double[] yval) // throws DimensionMismatchException, // NoDataException, // NullArgumentException; // } // // // Abstract Java Test Class // package org.apache.commons.math3.analysis.interpolation; // // import org.apache.commons.math3.analysis.MultivariateFunction; // import org.apache.commons.math3.util.FastMath; // import org.junit.Assert; // import org.junit.Test; // // // // public final class MicrosphereInterpolatorTest { // // // @Test // public void testLinearFunction2D(); // @Test // public void testParaboloid2D(); // public double value(double[] x); // public double value(double[] x); // } // You are a professional Java test case writer, please create a test case named `testParaboloid2D` for the `MicrosphereInterpolator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test of interpolator for a quadratic function. * <p> * y = 2 x<sub>1</sub><sup>2</sup> - 3 x<sub>2</sub><sup>2</sup> * + 4 x<sub>1</sub> x<sub>2</sub> - 5 */ @Test public void testParaboloid2D() {
/** * Test of interpolator for a quadratic function. * <p> * y = 2 x<sub>1</sub><sup>2</sup> - 3 x<sub>2</sub><sup>2</sup> * + 4 x<sub>1</sub> x<sub>2</sub> - 5 */
1
org.apache.commons.math3.analysis.interpolation.MicrosphereInterpolator
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.math3.analysis.interpolation; import org.apache.commons.math3.analysis.MultivariateFunction; import org.apache.commons.math3.exception.NotPositiveException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.NoDataException; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.random.UnitSphereRandomVectorGenerator; public class MicrosphereInterpolator implements MultivariateInterpolator { public static final int DEFAULT_MICROSPHERE_ELEMENTS = 2000; public static final int DEFAULT_BRIGHTNESS_EXPONENT = 2; private final int microsphereElements; private final int brightnessExponent; public MicrosphereInterpolator(); public MicrosphereInterpolator(final int elements, final int exponent) throws NotPositiveException, NotStrictlyPositiveException; public MultivariateFunction interpolate(final double[][] xval, final double[] yval) throws DimensionMismatchException, NoDataException, NullArgumentException; } // Abstract Java Test Class package org.apache.commons.math3.analysis.interpolation; import org.apache.commons.math3.analysis.MultivariateFunction; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; public final class MicrosphereInterpolatorTest { @Test public void testLinearFunction2D(); @Test public void testParaboloid2D(); public double value(double[] x); public double value(double[] x); } ``` You are a professional Java test case writer, please create a test case named `testParaboloid2D` for the `MicrosphereInterpolator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test of interpolator for a quadratic function. * <p> * y = 2 x<sub>1</sub><sup>2</sup> - 3 x<sub>2</sub><sup>2</sup> * + 4 x<sub>1</sub> x<sub>2</sub> - 5 */ @Test public void testParaboloid2D() { ```
public class MicrosphereInterpolator implements MultivariateInterpolator
package org.apache.commons.math3.analysis.interpolation; import org.apache.commons.math3.analysis.MultivariateFunction; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test;
@Test public void testLinearFunction2D(); @Test public void testParaboloid2D(); public double value(double[] x); public double value(double[] x);
3b1e1ce49c398277d4da07b37ad478ef597c33fff64cc4cb24ba16446bd98cb3
[ "org.apache.commons.math3.analysis.interpolation.MicrosphereInterpolatorTest::testParaboloid2D" ]
public static final int DEFAULT_MICROSPHERE_ELEMENTS = 2000; public static final int DEFAULT_BRIGHTNESS_EXPONENT = 2; private final int microsphereElements; private final int brightnessExponent;
@Test public void testParaboloid2D()
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.interpolation; import org.apache.commons.math3.analysis.MultivariateFunction; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; /** * Test case for the "microsphere projection" interpolator. * * @version $Id$ */ public final class MicrosphereInterpolatorTest { /** * Test of interpolator for a plane. * <p> * y = 2 x<sub>1</sub> - 3 x<sub>2</sub> + 5 */ @Test public void testLinearFunction2D() { MultivariateFunction f = new MultivariateFunction() { public double value(double[] x) { if (x.length != 2) { throw new IllegalArgumentException(); } return 2 * x[0] - 3 * x[1] + 5; } }; MultivariateInterpolator interpolator = new MicrosphereInterpolator(); // Interpolating points in [-1, 1][-1, 1] by steps of 1. final int n = 9; final int dim = 2; double[][] x = new double[n][dim]; double[] y = new double[n]; int index = 0; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { x[index][0] = i; x[index][1] = j; y[index] = f.value(x[index]); ++index; } } MultivariateFunction p = interpolator.interpolate(x, y); double[] c = new double[dim]; double expected, result; c[0] = 0; c[1] = 0; expected = f.value(c); result = p.value(c); Assert.assertEquals("On sample point", expected, result, FastMath.ulp(1d)); c[0] = 0 + 1e-5; c[1] = 1 - 1e-5; expected = f.value(c); result = p.value(c); Assert.assertEquals("1e-5 away from sample point", expected, result, 1e-4); } /** * Test of interpolator for a quadratic function. * <p> * y = 2 x<sub>1</sub><sup>2</sup> - 3 x<sub>2</sub><sup>2</sup> * + 4 x<sub>1</sub> x<sub>2</sub> - 5 */ @Test public void testParaboloid2D() { MultivariateFunction f = new MultivariateFunction() { public double value(double[] x) { if (x.length != 2) { throw new IllegalArgumentException(); } return 2 * x[0] * x[0] - 3 * x[1] * x[1] + 4 * x[0] * x[1] - 5; } }; MultivariateInterpolator interpolator = new MicrosphereInterpolator(); // Interpolating points in [-10, 10][-10, 10] by steps of 2. final int n = 121; final int dim = 2; double[][] x = new double[n][dim]; double[] y = new double[n]; int index = 0; for (int i = -10; i <= 10; i += 2) { for (int j = -10; j <= 10; j += 2) { x[index][0] = i; x[index][1] = j; y[index] = f.value(x[index]); ++index; } } MultivariateFunction p = interpolator.interpolate(x, y); double[] c = new double[dim]; double expected, result; c[0] = 0; c[1] = 0; expected = f.value(c); result = p.value(c); Assert.assertEquals("On sample point", expected, result, FastMath.ulp(1d)); c[0] = 2 + 1e-5; c[1] = 2 - 1e-5; expected = f.value(c); result = p.value(c); Assert.assertEquals("1e-5 away from sample point", expected, result, 1e-3); } }
[ { "be_test_class_file": "org/apache/commons/math3/analysis/interpolation/MicrosphereInterpolator.java", "be_test_class_name": "org.apache.commons.math3.analysis.interpolation.MicrosphereInterpolator", "be_test_function_name": "interpolate", "be_test_function_signature": "([[D[D)Lorg/apache/commons/math3/analysis/MultivariateFunction;", "line_numbers": [ "96", "98" ], "method_line_rate": 1 } ]
public class LevenbergMarquardtOptimizerTest extends AbstractLeastSquaresOptimizerAbstractTest
@Test public void testBevington() { final double[][] dataPoints = { // column 1 = times { 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180, 195, 210, 225, 240, 255, 270, 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 495, 510, 525, 540, 555, 570, 585, 600, 615, 630, 645, 660, 675, 690, 705, 720, 735, 750, 765, 780, 795, 810, 825, 840, 855, 870, 885, }, // column 2 = measured counts { 775, 479, 380, 302, 185, 157, 137, 119, 110, 89, 74, 61, 66, 68, 48, 54, 51, 46, 55, 29, 28, 37, 49, 26, 35, 29, 31, 24, 25, 35, 24, 30, 26, 28, 21, 18, 20, 27, 17, 17, 14, 17, 24, 11, 22, 17, 12, 10, 13, 16, 9, 9, 14, 21, 17, 13, 12, 18, 10, }, }; final BevingtonProblem problem = new BevingtonProblem(); final int len = dataPoints[0].length; final double[] weights = new double[len]; for (int i = 0; i < len; i++) { problem.addPoint(dataPoints[0][i], dataPoints[1][i]); weights[i] = 1 / dataPoints[1][i]; } final LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer(); final PointVectorValuePair optimum = optimizer.optimize(100, problem, dataPoints[1], weights, new double[] { 10, 900, 80, 27, 225 }); final double[] solution = optimum.getPoint(); final double[] expectedSolution = { 10.4, 958.3, 131.4, 33.9, 205.0 }; final double[][] covarMatrix = optimizer.computeCovariances(solution, 1e-14); final double[][] expectedCovarMatrix = { { 3.38, -3.69, 27.98, -2.34, -49.24 }, { -3.69, 2492.26, 81.89, -69.21, -8.9 }, { 27.98, 81.89, 468.99, -44.22, -615.44 }, { -2.34, -69.21, -44.22, 6.39, 53.80 }, { -49.24, -8.9, -615.44, 53.8, 929.45 } }; final int numParams = expectedSolution.length; // Check that the computed solution is within the reference error range. for (int i = 0; i < numParams; i++) { final double error = FastMath.sqrt(expectedCovarMatrix[i][i]); Assert.assertEquals("Parameter " + i, expectedSolution[i], solution[i], error); } // Check that each entry of the computed covariance matrix is within 10% // of the reference matrix entry. for (int i = 0; i < numParams; i++) { for (int j = 0; j < numParams; j++) { Assert.assertEquals("Covariance matrix [" + i + "][" + j + "]", expectedCovarMatrix[i][j], covarMatrix[i][j], FastMath.abs(0.1 * expectedCovarMatrix[i][j])); } } }
// // Abstract Java Tested Class // package org.apache.commons.math3.optimization.general; // // import java.util.Arrays; // import org.apache.commons.math3.exception.ConvergenceException; // import org.apache.commons.math3.exception.util.LocalizedFormats; // import org.apache.commons.math3.optimization.PointVectorValuePair; // import org.apache.commons.math3.optimization.ConvergenceChecker; // import org.apache.commons.math3.linear.RealMatrix; // import org.apache.commons.math3.util.Precision; // import org.apache.commons.math3.util.FastMath; // // // // @Deprecated // public class LevenbergMarquardtOptimizer extends AbstractLeastSquaresOptimizer { // private int solvedCols; // private double[] diagR; // private double[] jacNorm; // private double[] beta; // private int[] permutation; // private int rank; // private double lmPar; // private double[] lmDir; // private final double initialStepBoundFactor; // private final double costRelativeTolerance; // private final double parRelativeTolerance; // private final double orthoTolerance; // private final double qrRankingThreshold; // private double[] weightedResidual; // private double[][] weightedJacobian; // // public LevenbergMarquardtOptimizer(); // public LevenbergMarquardtOptimizer(ConvergenceChecker<PointVectorValuePair> checker); // public LevenbergMarquardtOptimizer(double initialStepBoundFactor, // ConvergenceChecker<PointVectorValuePair> checker, // double costRelativeTolerance, // double parRelativeTolerance, // double orthoTolerance, // double threshold); // public LevenbergMarquardtOptimizer(double costRelativeTolerance, // double parRelativeTolerance, // double orthoTolerance); // public LevenbergMarquardtOptimizer(double initialStepBoundFactor, // double costRelativeTolerance, // double parRelativeTolerance, // double orthoTolerance, // double threshold); // @Override // protected PointVectorValuePair doOptimize(); // private void determineLMParameter(double[] qy, double delta, double[] diag, // double[] work1, double[] work2, double[] work3); // private void determineLMDirection(double[] qy, double[] diag, // double[] lmDiag, double[] work); // private void qrDecomposition(RealMatrix jacobian) throws ConvergenceException; // private void qTy(double[] y); // } // // // Abstract Java Test Class // package org.apache.commons.math3.optimization.general; // // import java.io.Serializable; // import java.util.ArrayList; // import java.util.List; // import org.apache.commons.math3.analysis.differentiation.DerivativeStructure; // import org.apache.commons.math3.analysis.differentiation.MultivariateDifferentiableVectorFunction; // import org.apache.commons.math3.exception.ConvergenceException; // import org.apache.commons.math3.exception.DimensionMismatchException; // import org.apache.commons.math3.exception.TooManyEvaluationsException; // import org.apache.commons.math3.geometry.euclidean.twod.Vector2D; // import org.apache.commons.math3.linear.SingularMatrixException; // import org.apache.commons.math3.optimization.PointVectorValuePair; // import org.apache.commons.math3.util.FastMath; // import org.apache.commons.math3.util.Precision; // import org.junit.Assert; // import org.junit.Test; // import org.junit.Ignore; // // // // public class LevenbergMarquardtOptimizerTest extends AbstractLeastSquaresOptimizerAbstractTest { // // // @Override // public AbstractLeastSquaresOptimizer createOptimizer(); // @Override // @Test(expected=SingularMatrixException.class) // public void testNonInvertible(); // @Test // public void testControlParameters(); // private void checkEstimate(MultivariateDifferentiableVectorFunction problem, // double initialStepBoundFactor, int maxCostEval, // double costRelativeTolerance, double parRelativeTolerance, // double orthoTolerance, boolean shouldFail); // @Ignore@Test // public void testMath199(); // @Test // public void testBevington(); // @Test // public void testCircleFitting2(); // public QuadraticProblem(); // public void addPoint(double x, double y); // public double[] value(double[] variables); // public DerivativeStructure[] value(DerivativeStructure[] variables); // public BevingtonProblem(); // public void addPoint(double t, double c); // public double[] value(double[] params); // public DerivativeStructure[] value(DerivativeStructure[] params); // } // You are a professional Java test case writer, please create a test case named `testBevington` for the `LevenbergMarquardtOptimizer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Non-linear test case: fitting of decay curve (from Chapter 8 of * Bevington's textbook, "Data reduction and analysis for the physical sciences"). * XXX The expected ("reference") values may not be accurate and the tolerance too * relaxed for this test to be currently really useful (the issue is under * investigation). */
src/test/java/org/apache/commons/math3/optimization/general/LevenbergMarquardtOptimizerTest.java
package org.apache.commons.math3.optimization.general; import java.util.Arrays; import org.apache.commons.math3.exception.ConvergenceException; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.optimization.PointVectorValuePair; import org.apache.commons.math3.optimization.ConvergenceChecker; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.util.Precision; import org.apache.commons.math3.util.FastMath;
public LevenbergMarquardtOptimizer(); public LevenbergMarquardtOptimizer(ConvergenceChecker<PointVectorValuePair> checker); public LevenbergMarquardtOptimizer(double initialStepBoundFactor, ConvergenceChecker<PointVectorValuePair> checker, double costRelativeTolerance, double parRelativeTolerance, double orthoTolerance, double threshold); public LevenbergMarquardtOptimizer(double costRelativeTolerance, double parRelativeTolerance, double orthoTolerance); public LevenbergMarquardtOptimizer(double initialStepBoundFactor, double costRelativeTolerance, double parRelativeTolerance, double orthoTolerance, double threshold); @Override protected PointVectorValuePair doOptimize(); private void determineLMParameter(double[] qy, double delta, double[] diag, double[] work1, double[] work2, double[] work3); private void determineLMDirection(double[] qy, double[] diag, double[] lmDiag, double[] work); private void qrDecomposition(RealMatrix jacobian) throws ConvergenceException; private void qTy(double[] y);
259
testBevington
```java // Abstract Java Tested Class package org.apache.commons.math3.optimization.general; import java.util.Arrays; import org.apache.commons.math3.exception.ConvergenceException; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.optimization.PointVectorValuePair; import org.apache.commons.math3.optimization.ConvergenceChecker; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.util.Precision; import org.apache.commons.math3.util.FastMath; @Deprecated public class LevenbergMarquardtOptimizer extends AbstractLeastSquaresOptimizer { private int solvedCols; private double[] diagR; private double[] jacNorm; private double[] beta; private int[] permutation; private int rank; private double lmPar; private double[] lmDir; private final double initialStepBoundFactor; private final double costRelativeTolerance; private final double parRelativeTolerance; private final double orthoTolerance; private final double qrRankingThreshold; private double[] weightedResidual; private double[][] weightedJacobian; public LevenbergMarquardtOptimizer(); public LevenbergMarquardtOptimizer(ConvergenceChecker<PointVectorValuePair> checker); public LevenbergMarquardtOptimizer(double initialStepBoundFactor, ConvergenceChecker<PointVectorValuePair> checker, double costRelativeTolerance, double parRelativeTolerance, double orthoTolerance, double threshold); public LevenbergMarquardtOptimizer(double costRelativeTolerance, double parRelativeTolerance, double orthoTolerance); public LevenbergMarquardtOptimizer(double initialStepBoundFactor, double costRelativeTolerance, double parRelativeTolerance, double orthoTolerance, double threshold); @Override protected PointVectorValuePair doOptimize(); private void determineLMParameter(double[] qy, double delta, double[] diag, double[] work1, double[] work2, double[] work3); private void determineLMDirection(double[] qy, double[] diag, double[] lmDiag, double[] work); private void qrDecomposition(RealMatrix jacobian) throws ConvergenceException; private void qTy(double[] y); } // Abstract Java Test Class package org.apache.commons.math3.optimization.general; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.analysis.differentiation.DerivativeStructure; import org.apache.commons.math3.analysis.differentiation.MultivariateDifferentiableVectorFunction; import org.apache.commons.math3.exception.ConvergenceException; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.TooManyEvaluationsException; import org.apache.commons.math3.geometry.euclidean.twod.Vector2D; import org.apache.commons.math3.linear.SingularMatrixException; import org.apache.commons.math3.optimization.PointVectorValuePair; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.Precision; import org.junit.Assert; import org.junit.Test; import org.junit.Ignore; public class LevenbergMarquardtOptimizerTest extends AbstractLeastSquaresOptimizerAbstractTest { @Override public AbstractLeastSquaresOptimizer createOptimizer(); @Override @Test(expected=SingularMatrixException.class) public void testNonInvertible(); @Test public void testControlParameters(); private void checkEstimate(MultivariateDifferentiableVectorFunction problem, double initialStepBoundFactor, int maxCostEval, double costRelativeTolerance, double parRelativeTolerance, double orthoTolerance, boolean shouldFail); @Ignore@Test public void testMath199(); @Test public void testBevington(); @Test public void testCircleFitting2(); public QuadraticProblem(); public void addPoint(double x, double y); public double[] value(double[] variables); public DerivativeStructure[] value(DerivativeStructure[] variables); public BevingtonProblem(); public void addPoint(double t, double c); public double[] value(double[] params); public DerivativeStructure[] value(DerivativeStructure[] params); } ``` You are a professional Java test case writer, please create a test case named `testBevington` for the `LevenbergMarquardtOptimizer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Non-linear test case: fitting of decay curve (from Chapter 8 of * Bevington's textbook, "Data reduction and analysis for the physical sciences"). * XXX The expected ("reference") values may not be accurate and the tolerance too * relaxed for this test to be currently really useful (the issue is under * investigation). */
192
// // Abstract Java Tested Class // package org.apache.commons.math3.optimization.general; // // import java.util.Arrays; // import org.apache.commons.math3.exception.ConvergenceException; // import org.apache.commons.math3.exception.util.LocalizedFormats; // import org.apache.commons.math3.optimization.PointVectorValuePair; // import org.apache.commons.math3.optimization.ConvergenceChecker; // import org.apache.commons.math3.linear.RealMatrix; // import org.apache.commons.math3.util.Precision; // import org.apache.commons.math3.util.FastMath; // // // // @Deprecated // public class LevenbergMarquardtOptimizer extends AbstractLeastSquaresOptimizer { // private int solvedCols; // private double[] diagR; // private double[] jacNorm; // private double[] beta; // private int[] permutation; // private int rank; // private double lmPar; // private double[] lmDir; // private final double initialStepBoundFactor; // private final double costRelativeTolerance; // private final double parRelativeTolerance; // private final double orthoTolerance; // private final double qrRankingThreshold; // private double[] weightedResidual; // private double[][] weightedJacobian; // // public LevenbergMarquardtOptimizer(); // public LevenbergMarquardtOptimizer(ConvergenceChecker<PointVectorValuePair> checker); // public LevenbergMarquardtOptimizer(double initialStepBoundFactor, // ConvergenceChecker<PointVectorValuePair> checker, // double costRelativeTolerance, // double parRelativeTolerance, // double orthoTolerance, // double threshold); // public LevenbergMarquardtOptimizer(double costRelativeTolerance, // double parRelativeTolerance, // double orthoTolerance); // public LevenbergMarquardtOptimizer(double initialStepBoundFactor, // double costRelativeTolerance, // double parRelativeTolerance, // double orthoTolerance, // double threshold); // @Override // protected PointVectorValuePair doOptimize(); // private void determineLMParameter(double[] qy, double delta, double[] diag, // double[] work1, double[] work2, double[] work3); // private void determineLMDirection(double[] qy, double[] diag, // double[] lmDiag, double[] work); // private void qrDecomposition(RealMatrix jacobian) throws ConvergenceException; // private void qTy(double[] y); // } // // // Abstract Java Test Class // package org.apache.commons.math3.optimization.general; // // import java.io.Serializable; // import java.util.ArrayList; // import java.util.List; // import org.apache.commons.math3.analysis.differentiation.DerivativeStructure; // import org.apache.commons.math3.analysis.differentiation.MultivariateDifferentiableVectorFunction; // import org.apache.commons.math3.exception.ConvergenceException; // import org.apache.commons.math3.exception.DimensionMismatchException; // import org.apache.commons.math3.exception.TooManyEvaluationsException; // import org.apache.commons.math3.geometry.euclidean.twod.Vector2D; // import org.apache.commons.math3.linear.SingularMatrixException; // import org.apache.commons.math3.optimization.PointVectorValuePair; // import org.apache.commons.math3.util.FastMath; // import org.apache.commons.math3.util.Precision; // import org.junit.Assert; // import org.junit.Test; // import org.junit.Ignore; // // // // public class LevenbergMarquardtOptimizerTest extends AbstractLeastSquaresOptimizerAbstractTest { // // // @Override // public AbstractLeastSquaresOptimizer createOptimizer(); // @Override // @Test(expected=SingularMatrixException.class) // public void testNonInvertible(); // @Test // public void testControlParameters(); // private void checkEstimate(MultivariateDifferentiableVectorFunction problem, // double initialStepBoundFactor, int maxCostEval, // double costRelativeTolerance, double parRelativeTolerance, // double orthoTolerance, boolean shouldFail); // @Ignore@Test // public void testMath199(); // @Test // public void testBevington(); // @Test // public void testCircleFitting2(); // public QuadraticProblem(); // public void addPoint(double x, double y); // public double[] value(double[] variables); // public DerivativeStructure[] value(DerivativeStructure[] variables); // public BevingtonProblem(); // public void addPoint(double t, double c); // public double[] value(double[] params); // public DerivativeStructure[] value(DerivativeStructure[] params); // } // You are a professional Java test case writer, please create a test case named `testBevington` for the `LevenbergMarquardtOptimizer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Non-linear test case: fitting of decay curve (from Chapter 8 of * Bevington's textbook, "Data reduction and analysis for the physical sciences"). * XXX The expected ("reference") values may not be accurate and the tolerance too * relaxed for this test to be currently really useful (the issue is under * investigation). */ @Test public void testBevington() {
/** * Non-linear test case: fitting of decay curve (from Chapter 8 of * Bevington's textbook, "Data reduction and analysis for the physical sciences"). * XXX The expected ("reference") values may not be accurate and the tolerance too * relaxed for this test to be currently really useful (the issue is under * investigation). */
1
org.apache.commons.math3.optimization.general.LevenbergMarquardtOptimizer
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.math3.optimization.general; import java.util.Arrays; import org.apache.commons.math3.exception.ConvergenceException; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.optimization.PointVectorValuePair; import org.apache.commons.math3.optimization.ConvergenceChecker; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.util.Precision; import org.apache.commons.math3.util.FastMath; @Deprecated public class LevenbergMarquardtOptimizer extends AbstractLeastSquaresOptimizer { private int solvedCols; private double[] diagR; private double[] jacNorm; private double[] beta; private int[] permutation; private int rank; private double lmPar; private double[] lmDir; private final double initialStepBoundFactor; private final double costRelativeTolerance; private final double parRelativeTolerance; private final double orthoTolerance; private final double qrRankingThreshold; private double[] weightedResidual; private double[][] weightedJacobian; public LevenbergMarquardtOptimizer(); public LevenbergMarquardtOptimizer(ConvergenceChecker<PointVectorValuePair> checker); public LevenbergMarquardtOptimizer(double initialStepBoundFactor, ConvergenceChecker<PointVectorValuePair> checker, double costRelativeTolerance, double parRelativeTolerance, double orthoTolerance, double threshold); public LevenbergMarquardtOptimizer(double costRelativeTolerance, double parRelativeTolerance, double orthoTolerance); public LevenbergMarquardtOptimizer(double initialStepBoundFactor, double costRelativeTolerance, double parRelativeTolerance, double orthoTolerance, double threshold); @Override protected PointVectorValuePair doOptimize(); private void determineLMParameter(double[] qy, double delta, double[] diag, double[] work1, double[] work2, double[] work3); private void determineLMDirection(double[] qy, double[] diag, double[] lmDiag, double[] work); private void qrDecomposition(RealMatrix jacobian) throws ConvergenceException; private void qTy(double[] y); } // Abstract Java Test Class package org.apache.commons.math3.optimization.general; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.analysis.differentiation.DerivativeStructure; import org.apache.commons.math3.analysis.differentiation.MultivariateDifferentiableVectorFunction; import org.apache.commons.math3.exception.ConvergenceException; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.TooManyEvaluationsException; import org.apache.commons.math3.geometry.euclidean.twod.Vector2D; import org.apache.commons.math3.linear.SingularMatrixException; import org.apache.commons.math3.optimization.PointVectorValuePair; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.Precision; import org.junit.Assert; import org.junit.Test; import org.junit.Ignore; public class LevenbergMarquardtOptimizerTest extends AbstractLeastSquaresOptimizerAbstractTest { @Override public AbstractLeastSquaresOptimizer createOptimizer(); @Override @Test(expected=SingularMatrixException.class) public void testNonInvertible(); @Test public void testControlParameters(); private void checkEstimate(MultivariateDifferentiableVectorFunction problem, double initialStepBoundFactor, int maxCostEval, double costRelativeTolerance, double parRelativeTolerance, double orthoTolerance, boolean shouldFail); @Ignore@Test public void testMath199(); @Test public void testBevington(); @Test public void testCircleFitting2(); public QuadraticProblem(); public void addPoint(double x, double y); public double[] value(double[] variables); public DerivativeStructure[] value(DerivativeStructure[] variables); public BevingtonProblem(); public void addPoint(double t, double c); public double[] value(double[] params); public DerivativeStructure[] value(DerivativeStructure[] params); } ``` You are a professional Java test case writer, please create a test case named `testBevington` for the `LevenbergMarquardtOptimizer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Non-linear test case: fitting of decay curve (from Chapter 8 of * Bevington's textbook, "Data reduction and analysis for the physical sciences"). * XXX The expected ("reference") values may not be accurate and the tolerance too * relaxed for this test to be currently really useful (the issue is under * investigation). */ @Test public void testBevington() { ```
@Deprecated public class LevenbergMarquardtOptimizer extends AbstractLeastSquaresOptimizer
package org.apache.commons.math3.optimization.general; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.analysis.differentiation.DerivativeStructure; import org.apache.commons.math3.analysis.differentiation.MultivariateDifferentiableVectorFunction; import org.apache.commons.math3.exception.ConvergenceException; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.TooManyEvaluationsException; import org.apache.commons.math3.geometry.euclidean.twod.Vector2D; import org.apache.commons.math3.linear.SingularMatrixException; import org.apache.commons.math3.optimization.PointVectorValuePair; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.Precision; import org.junit.Assert; import org.junit.Test; import org.junit.Ignore;
@Override public AbstractLeastSquaresOptimizer createOptimizer(); @Override @Test(expected=SingularMatrixException.class) public void testNonInvertible(); @Test public void testControlParameters(); private void checkEstimate(MultivariateDifferentiableVectorFunction problem, double initialStepBoundFactor, int maxCostEval, double costRelativeTolerance, double parRelativeTolerance, double orthoTolerance, boolean shouldFail); @Ignore@Test public void testMath199(); @Test public void testBevington(); @Test public void testCircleFitting2(); public QuadraticProblem(); public void addPoint(double x, double y); public double[] value(double[] variables); public DerivativeStructure[] value(DerivativeStructure[] variables); public BevingtonProblem(); public void addPoint(double t, double c); public double[] value(double[] params); public DerivativeStructure[] value(DerivativeStructure[] params);
3b5cd1037557885b2982e66a0cf63e86f5d031b5e6dd7f75eb234208bc60a80a
[ "org.apache.commons.math3.optimization.general.LevenbergMarquardtOptimizerTest::testBevington" ]
private int solvedCols; private double[] diagR; private double[] jacNorm; private double[] beta; private int[] permutation; private int rank; private double lmPar; private double[] lmDir; private final double initialStepBoundFactor; private final double costRelativeTolerance; private final double parRelativeTolerance; private final double orthoTolerance; private final double qrRankingThreshold; private double[] weightedResidual; private double[][] weightedJacobian;
@Test public void testBevington()
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.optimization.general; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.analysis.differentiation.DerivativeStructure; import org.apache.commons.math3.analysis.differentiation.MultivariateDifferentiableVectorFunction; import org.apache.commons.math3.exception.ConvergenceException; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.TooManyEvaluationsException; import org.apache.commons.math3.geometry.euclidean.twod.Vector2D; import org.apache.commons.math3.linear.SingularMatrixException; import org.apache.commons.math3.optimization.PointVectorValuePair; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.Precision; import org.junit.Assert; import org.junit.Test; import org.junit.Ignore; /** * <p>Some of the unit tests are re-implementations of the MINPACK <a * href="http://www.netlib.org/minpack/ex/file17">file17</a> and <a * href="http://www.netlib.org/minpack/ex/file22">file22</a> test files. * The redistribution policy for MINPACK is available <a * href="http://www.netlib.org/minpack/disclaimer">here</a>, for * convenience, it is reproduced below.</p> * <table border="0" width="80%" cellpadding="10" align="center" bgcolor="#E0E0E0"> * <tr><td> * Minpack Copyright Notice (1999) University of Chicago. * All rights reserved * </td></tr> * <tr><td> * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * <ol> * <li>Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer.</li> * <li>Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution.</li> * <li>The end-user documentation included with the redistribution, if any, * must include the following acknowledgment: * <code>This product includes software developed by the University of * Chicago, as Operator of Argonne National Laboratory.</code> * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear.</li> * <li><strong>WARRANTY DISCLAIMER. THE SOFTWARE IS SUPPLIED "AS IS" * WITHOUT WARRANTY OF ANY KIND. THE COPYRIGHT HOLDER, THE * UNITED STATES, THE UNITED STATES DEPARTMENT OF ENERGY, AND * THEIR EMPLOYEES: (1) DISCLAIM ANY WARRANTIES, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO ANY IMPLIED WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE * OR NON-INFRINGEMENT, (2) DO NOT ASSUME ANY LEGAL LIABILITY * OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS, OR * USEFULNESS OF THE SOFTWARE, (3) DO NOT REPRESENT THAT USE OF * THE SOFTWARE WOULD NOT INFRINGE PRIVATELY OWNED RIGHTS, (4) * DO NOT WARRANT THAT THE SOFTWARE WILL FUNCTION * UNINTERRUPTED, THAT IT IS ERROR-FREE OR THAT ANY ERRORS WILL * BE CORRECTED.</strong></li> * <li><strong>LIMITATION OF LIABILITY. IN NO EVENT WILL THE COPYRIGHT * HOLDER, THE UNITED STATES, THE UNITED STATES DEPARTMENT OF * ENERGY, OR THEIR EMPLOYEES: BE LIABLE FOR ANY INDIRECT, * INCIDENTAL, CONSEQUENTIAL, SPECIAL OR PUNITIVE DAMAGES OF * ANY KIND OR NATURE, INCLUDING BUT NOT LIMITED TO LOSS OF * PROFITS OR LOSS OF DATA, FOR ANY REASON WHATSOEVER, WHETHER * SUCH LIABILITY IS ASSERTED ON THE BASIS OF CONTRACT, TORT * (INCLUDING NEGLIGENCE OR STRICT LIABILITY), OR OTHERWISE, * EVEN IF ANY OF SAID PARTIES HAS BEEN WARNED OF THE * POSSIBILITY OF SUCH LOSS OR DAMAGES.</strong></li> * <ol></td></tr> * </table> * @author Argonne National Laboratory. MINPACK project. March 1980 (original fortran minpack tests) * @author Burton S. Garbow (original fortran minpack tests) * @author Kenneth E. Hillstrom (original fortran minpack tests) * @author Jorge J. More (original fortran minpack tests) * @author Luc Maisonobe (non-minpack tests and minpack tests Java translation) */ public class LevenbergMarquardtOptimizerTest extends AbstractLeastSquaresOptimizerAbstractTest { @Override public AbstractLeastSquaresOptimizer createOptimizer() { return new LevenbergMarquardtOptimizer(); } @Override @Test(expected=SingularMatrixException.class) public void testNonInvertible() { /* * Overrides the method from parent class, since the default singularity * threshold (1e-14) does not trigger the expected exception. */ LinearProblem problem = new LinearProblem(new double[][] { { 1, 2, -3 }, { 2, 1, 3 }, { -3, 0, -9 } }, new double[] { 1, 1, 1 }); AbstractLeastSquaresOptimizer optimizer = createOptimizer(); PointVectorValuePair optimum = optimizer.optimize(100, problem, problem.target, new double[] { 1, 1, 1 }, new double[] { 0, 0, 0 }); Assert.assertTrue(FastMath.sqrt(problem.target.length) * optimizer.getRMS() > 0.6); optimizer.computeCovariances(optimum.getPoint(), 1.5e-14); } @Test public void testControlParameters() { CircleVectorial circle = new CircleVectorial(); circle.addPoint( 30.0, 68.0); circle.addPoint( 50.0, -6.0); circle.addPoint(110.0, -20.0); circle.addPoint( 35.0, 15.0); circle.addPoint( 45.0, 97.0); checkEstimate(circle, 0.1, 10, 1.0e-14, 1.0e-16, 1.0e-10, false); checkEstimate(circle, 0.1, 10, 1.0e-15, 1.0e-17, 1.0e-10, true); checkEstimate(circle, 0.1, 5, 1.0e-15, 1.0e-16, 1.0e-10, true); circle.addPoint(300, -300); checkEstimate(circle, 0.1, 20, 1.0e-18, 1.0e-16, 1.0e-10, true); } private void checkEstimate(MultivariateDifferentiableVectorFunction problem, double initialStepBoundFactor, int maxCostEval, double costRelativeTolerance, double parRelativeTolerance, double orthoTolerance, boolean shouldFail) { try { LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer(initialStepBoundFactor, costRelativeTolerance, parRelativeTolerance, orthoTolerance, Precision.SAFE_MIN); optimizer.optimize(maxCostEval, problem, new double[] { 0, 0, 0, 0, 0 }, new double[] { 1, 1, 1, 1, 1 }, new double[] { 98.680, 47.345 }); Assert.assertTrue(!shouldFail); } catch (DimensionMismatchException ee) { Assert.assertTrue(shouldFail); } catch (TooManyEvaluationsException ee) { Assert.assertTrue(shouldFail); } } // Test is skipped because it fails with the latest code update. @Ignore@Test public void testMath199() { try { QuadraticProblem problem = new QuadraticProblem(); problem.addPoint (0, -3.182591015485607); problem.addPoint (1, -2.5581184967730577); problem.addPoint (2, -2.1488478161387325); problem.addPoint (3, -1.9122489313410047); problem.addPoint (4, 1.7785661310051026); LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer(100, 1e-10, 1e-10, 1e-10, 0); optimizer.optimize(100, problem, new double[] { 0, 0, 0, 0, 0 }, new double[] { 0.0, 4.4e-323, 1.0, 4.4e-323, 0.0 }, new double[] { 0, 0, 0 }); Assert.fail("an exception should have been thrown"); } catch (ConvergenceException ee) { // expected behavior } } /** * Non-linear test case: fitting of decay curve (from Chapter 8 of * Bevington's textbook, "Data reduction and analysis for the physical sciences"). * XXX The expected ("reference") values may not be accurate and the tolerance too * relaxed for this test to be currently really useful (the issue is under * investigation). */ @Test public void testBevington() { final double[][] dataPoints = { // column 1 = times { 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180, 195, 210, 225, 240, 255, 270, 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 495, 510, 525, 540, 555, 570, 585, 600, 615, 630, 645, 660, 675, 690, 705, 720, 735, 750, 765, 780, 795, 810, 825, 840, 855, 870, 885, }, // column 2 = measured counts { 775, 479, 380, 302, 185, 157, 137, 119, 110, 89, 74, 61, 66, 68, 48, 54, 51, 46, 55, 29, 28, 37, 49, 26, 35, 29, 31, 24, 25, 35, 24, 30, 26, 28, 21, 18, 20, 27, 17, 17, 14, 17, 24, 11, 22, 17, 12, 10, 13, 16, 9, 9, 14, 21, 17, 13, 12, 18, 10, }, }; final BevingtonProblem problem = new BevingtonProblem(); final int len = dataPoints[0].length; final double[] weights = new double[len]; for (int i = 0; i < len; i++) { problem.addPoint(dataPoints[0][i], dataPoints[1][i]); weights[i] = 1 / dataPoints[1][i]; } final LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer(); final PointVectorValuePair optimum = optimizer.optimize(100, problem, dataPoints[1], weights, new double[] { 10, 900, 80, 27, 225 }); final double[] solution = optimum.getPoint(); final double[] expectedSolution = { 10.4, 958.3, 131.4, 33.9, 205.0 }; final double[][] covarMatrix = optimizer.computeCovariances(solution, 1e-14); final double[][] expectedCovarMatrix = { { 3.38, -3.69, 27.98, -2.34, -49.24 }, { -3.69, 2492.26, 81.89, -69.21, -8.9 }, { 27.98, 81.89, 468.99, -44.22, -615.44 }, { -2.34, -69.21, -44.22, 6.39, 53.80 }, { -49.24, -8.9, -615.44, 53.8, 929.45 } }; final int numParams = expectedSolution.length; // Check that the computed solution is within the reference error range. for (int i = 0; i < numParams; i++) { final double error = FastMath.sqrt(expectedCovarMatrix[i][i]); Assert.assertEquals("Parameter " + i, expectedSolution[i], solution[i], error); } // Check that each entry of the computed covariance matrix is within 10% // of the reference matrix entry. for (int i = 0; i < numParams; i++) { for (int j = 0; j < numParams; j++) { Assert.assertEquals("Covariance matrix [" + i + "][" + j + "]", expectedCovarMatrix[i][j], covarMatrix[i][j], FastMath.abs(0.1 * expectedCovarMatrix[i][j])); } } } @Test public void testCircleFitting2() { final double xCenter = 123.456; final double yCenter = 654.321; final double xSigma = 10; final double ySigma = 15; final double radius = 111.111; // The test is extremely sensitive to the seed. final long seed = 59421061L; final RandomCirclePointGenerator factory = new RandomCirclePointGenerator(xCenter, yCenter, radius, xSigma, ySigma, seed); final CircleProblem circle = new CircleProblem(xSigma, ySigma); final int numPoints = 10; for (Vector2D p : factory.generate(numPoints)) { circle.addPoint(p); // System.out.println(p.x + " " + p.y); } // First guess for the center's coordinates and radius. final double[] init = { 90, 659, 115 }; final LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer(); final PointVectorValuePair optimum = optimizer.optimize(100, circle, circle.target(), circle.weight(), init); final double[] paramFound = optimum.getPoint(); // Retrieve errors estimation. final double[][] covMatrix = optimizer.computeCovariances(paramFound, 1e-14); final double[] asymptoticStandardErrorFound = optimizer.guessParametersErrors(); final double[] sigmaFound = new double[covMatrix.length]; for (int i = 0; i < covMatrix.length; i++) { sigmaFound[i] = FastMath.sqrt(covMatrix[i][i]); // System.out.println("i=" + i + " value=" + paramFound[i] // + " sigma=" + sigmaFound[i] // + " ase=" + asymptoticStandardErrorFound[i]); } // System.out.println("chi2=" + optimizer.getChiSquare()); // Check that the parameters are found within the assumed error bars. Assert.assertEquals(xCenter, paramFound[0], asymptoticStandardErrorFound[0]); Assert.assertEquals(yCenter, paramFound[1], asymptoticStandardErrorFound[1]); Assert.assertEquals(radius, paramFound[2], asymptoticStandardErrorFound[2]); } private static class QuadraticProblem implements MultivariateDifferentiableVectorFunction, Serializable { private static final long serialVersionUID = 7072187082052755854L; private List<Double> x; private List<Double> y; public QuadraticProblem() { x = new ArrayList<Double>(); y = new ArrayList<Double>(); } public void addPoint(double x, double y) { this.x.add(x); this.y.add(y); } public double[] value(double[] variables) { double[] values = new double[x.size()]; for (int i = 0; i < values.length; ++i) { values[i] = (variables[0] * x.get(i) + variables[1]) * x.get(i) + variables[2]; } return values; } public DerivativeStructure[] value(DerivativeStructure[] variables) { DerivativeStructure[] values = new DerivativeStructure[x.size()]; for (int i = 0; i < values.length; ++i) { values[i] = (variables[0].multiply(x.get(i)).add(variables[1])).multiply(x.get(i)).add(variables[2]); } return values; } } private static class BevingtonProblem implements MultivariateDifferentiableVectorFunction { private List<Double> time; private List<Double> count; public BevingtonProblem() { time = new ArrayList<Double>(); count = new ArrayList<Double>(); } public void addPoint(double t, double c) { time.add(t); count.add(c); } public double[] value(double[] params) { double[] values = new double[time.size()]; for (int i = 0; i < values.length; ++i) { final double t = time.get(i); values[i] = params[0] + params[1] * Math.exp(-t / params[3]) + params[2] * Math.exp(-t / params[4]); } return values; } public DerivativeStructure[] value(DerivativeStructure[] params) { DerivativeStructure[] values = new DerivativeStructure[time.size()]; for (int i = 0; i < values.length; ++i) { final double t = time.get(i); values[i] = params[0].add( params[1].multiply(params[3].reciprocal().multiply(-t).exp())).add( params[2].multiply(params[4].reciprocal().multiply(-t).exp())); } return values; } } }
[ { "be_test_class_file": "org/apache/commons/math3/optimization/general/LevenbergMarquardtOptimizer.java", "be_test_class_name": "org.apache.commons.math3.optimization.general.LevenbergMarquardtOptimizer", "be_test_function_name": "determineLMParameter", "be_test_function_signature": "([DD[D[D[D[D)V", "line_numbers": [ "557", "561", "562", "564", "565", "567", "568", "569", "570", "571", "573", "578", "579", "580", "581", "582", "583", "585", "586", "587", "588", "589", "596", "597", "598", "599", "600", "602", "603", "604", "605", "606", "607", "609", "610", "611", "613", "617", "618", "619", "620", "621", "622", "624", "625", "627", "628", "629", "631", "636", "637", "638", "641", "644", "645", "647", "648", "649", "650", "652", "654", "655", "656", "657", "658", "659", "661", "662", "663", "667", "669", "673", "674", "675", "677", "678", "679", "680", "681", "682", "685", "686", "687", "688", "690", "693", "694", "695", "696", "700", "703" ], "method_line_rate": 0.23076923076923078 }, { "be_test_class_file": "org/apache/commons/math3/optimization/general/LevenbergMarquardtOptimizer.java", "be_test_class_name": "org.apache.commons.math3.optimization.general.LevenbergMarquardtOptimizer", "be_test_function_name": "doOptimize", "be_test_function_signature": "()Lorg/apache/commons/math3/optimization/PointVectorValuePair;", "line_numbers": [ "281", "282", "283", "286", "287", "288", "289", "290", "291", "294", "295", "296", "297", "298", "299", "300", "301", "302", "303", "305", "308", "309", "310", "311", "314", "315", "316", "317", "319", "320", "323", "325", "326", "327", "331", "335", "336", "337", "340", "343", "344", "345", "346", "347", "349", "350", "351", "353", "356", "360", "361", "362", "363", "364", "365", "366", "367", "368", "370", "374", "376", "378", "379", "383", "384", "388", "391", "392", "393", "395", "396", "397", "398", "399", "400", "401", "404", "407", "408", "409", "410", "411", "412", "413", "415", "417", "418", "422", "423", "424", "425", "428", "429", "430", "431", "436", "437", "438", "439", "440", "441", "444", "445", "446", "448", "449", "450", "451", "452", "455", "458", "459", "461", "462", "464", "465", "466", "467", "468", "472", "474", "475", "476", "477", "478", "480", "483", "484", "486", "487", "491", "492", "493", "494", "496", "497", "498", "499", "500", "501", "503", "507", "511", "513", "514", "519", "520", "522", "523", "525", "526", "529", "530" ], "method_line_rate": 0.8235294117647058 }, { "be_test_class_file": "org/apache/commons/math3/optimization/general/LevenbergMarquardtOptimizer.java", "be_test_class_name": "org.apache.commons.math3.optimization.general.LevenbergMarquardtOptimizer", "be_test_function_name": "qTy", "be_test_function_signature": "([D)V", "line_numbers": [ "929", "930", "932", "933", "934", "935", "936", "938", "939", "940", "943" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/optimization/general/LevenbergMarquardtOptimizer.java", "be_test_class_name": "org.apache.commons.math3.optimization.general.LevenbergMarquardtOptimizer", "be_test_function_name": "qrDecomposition", "be_test_function_signature": "(Lorg/apache/commons/math3/linear/RealMatrix;)V", "line_numbers": [ "853", "855", "856", "859", "860", "861", "862", "863", "864", "866", "870", "873", "874", "875", "876", "877", "878", "879", "881", "882", "885", "886", "887", "890", "891", "892", "894", "895", "896", "899", "900", "901", "902", "905", "906", "909", "910", "911", "912", "914", "915", "916", "920", "921" ], "method_line_rate": 0.9318181818181818 } ]
public class LocaleUtilsTest
@Test public void testAvailableLocaleSet() { final Set<Locale> set = LocaleUtils.availableLocaleSet(); final Set<Locale> set2 = LocaleUtils.availableLocaleSet(); assertNotNull(set); assertSame(set, set2); assertUnmodifiableCollection(set); final Locale[] jdkLocaleArray = Locale.getAvailableLocales(); final List<Locale> jdkLocaleList = Arrays.asList(jdkLocaleArray); final Set<Locale> jdkLocaleSet = new HashSet<Locale>(jdkLocaleList); assertEquals(jdkLocaleSet, set); }
// // Abstract Java Tested Class // package org.apache.commons.lang3; // // import java.util.ArrayList; // import java.util.Arrays; // import java.util.Collections; // import java.util.HashSet; // import java.util.List; // import java.util.Locale; // import java.util.Set; // import java.util.concurrent.ConcurrentHashMap; // import java.util.concurrent.ConcurrentMap; // // // // public class LocaleUtils { // private static final ConcurrentMap<String, List<Locale>> cLanguagesByCountry = // new ConcurrentHashMap<String, List<Locale>>(); // private static final ConcurrentMap<String, List<Locale>> cCountriesByLanguage = // new ConcurrentHashMap<String, List<Locale>>(); // // public LocaleUtils(); // public static Locale toLocale(final String str); // public static List<Locale> localeLookupList(final Locale locale); // public static List<Locale> localeLookupList(final Locale locale, final Locale defaultLocale); // public static List<Locale> availableLocaleList(); // public static Set<Locale> availableLocaleSet(); // public static boolean isAvailableLocale(final Locale locale); // public static List<Locale> languagesByCountry(final String countryCode); // public static List<Locale> countriesByLanguage(final String languageCode); // } // // // Abstract Java Test Class // package org.apache.commons.lang3; // // 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.assertSame; // import static org.junit.Assert.assertTrue; // import static org.junit.Assert.fail; // import java.lang.reflect.Constructor; // import java.lang.reflect.Modifier; // import java.util.Arrays; // import java.util.Collection; // import java.util.HashSet; // import java.util.Iterator; // import java.util.List; // import java.util.Locale; // import java.util.Set; // import org.junit.Before; // import org.junit.Test; // // // // public class LocaleUtilsTest { // private static final Locale LOCALE_EN = new Locale("en", ""); // private static final Locale LOCALE_EN_US = new Locale("en", "US"); // private static final Locale LOCALE_EN_US_ZZZZ = new Locale("en", "US", "ZZZZ"); // private static final Locale LOCALE_FR = new Locale("fr", ""); // private static final Locale LOCALE_FR_CA = new Locale("fr", "CA"); // private static final Locale LOCALE_QQ = new Locale("qq", ""); // private static final Locale LOCALE_QQ_ZZ = new Locale("qq", "ZZ"); // // @Before // public void setUp() throws Exception; // @Test // public void testConstructor(); // private void assertValidToLocale(final String language); // private void assertValidToLocale(final String localeString, final String language, final String country); // private void assertValidToLocale( // final String localeString, final String language, // final String country, final String variant); // @Test // public void testToLocale_1Part(); // @Test // public void testToLocale_2Part(); // @Test // public void testToLocale_3Part(); // private void assertLocaleLookupList(final Locale locale, final Locale defaultLocale, final Locale[] expected); // @Test // public void testLocaleLookupList_Locale(); // @Test // public void testLocaleLookupList_LocaleLocale(); // @Test // public void testAvailableLocaleList(); // @Test // public void testAvailableLocaleSet(); // @SuppressWarnings("boxing") // JUnit4 does not support primitive equality testing apart from long // @Test // public void testIsAvailableLocale(); // private void assertLanguageByCountry(final String country, final String[] languages); // @Test // public void testLanguagesByCountry(); // private void assertCountriesByLanguage(final String language, final String[] countries); // @Test // public void testCountriesByLanguage(); // private static void assertUnmodifiableCollection(final Collection<?> coll); // @Test // public void testLang328(); // @Test // public void testLang865(); // @Test // public void testParseAllLocales(); // } // You are a professional Java test case writer, please create a test case named `testAvailableLocaleSet` for the `LocaleUtils` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test availableLocaleSet() method. */
src/test/java/org/apache/commons/lang3/LocaleUtilsTest.java
package org.apache.commons.lang3; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap;
public LocaleUtils(); public static Locale toLocale(final String str); public static List<Locale> localeLookupList(final Locale locale); public static List<Locale> localeLookupList(final Locale locale, final Locale defaultLocale); public static List<Locale> availableLocaleList(); public static Set<Locale> availableLocaleSet(); public static boolean isAvailableLocale(final Locale locale); public static List<Locale> languagesByCountry(final String countryCode); public static List<Locale> countriesByLanguage(final String languageCode);
360
testAvailableLocaleSet
```java // Abstract Java Tested Class package org.apache.commons.lang3; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class LocaleUtils { private static final ConcurrentMap<String, List<Locale>> cLanguagesByCountry = new ConcurrentHashMap<String, List<Locale>>(); private static final ConcurrentMap<String, List<Locale>> cCountriesByLanguage = new ConcurrentHashMap<String, List<Locale>>(); public LocaleUtils(); public static Locale toLocale(final String str); public static List<Locale> localeLookupList(final Locale locale); public static List<Locale> localeLookupList(final Locale locale, final Locale defaultLocale); public static List<Locale> availableLocaleList(); public static Set<Locale> availableLocaleSet(); public static boolean isAvailableLocale(final Locale locale); public static List<Locale> languagesByCountry(final String countryCode); public static List<Locale> countriesByLanguage(final String languageCode); } // Abstract Java Test Class package org.apache.commons.lang3; 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.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Set; import org.junit.Before; import org.junit.Test; public class LocaleUtilsTest { private static final Locale LOCALE_EN = new Locale("en", ""); private static final Locale LOCALE_EN_US = new Locale("en", "US"); private static final Locale LOCALE_EN_US_ZZZZ = new Locale("en", "US", "ZZZZ"); private static final Locale LOCALE_FR = new Locale("fr", ""); private static final Locale LOCALE_FR_CA = new Locale("fr", "CA"); private static final Locale LOCALE_QQ = new Locale("qq", ""); private static final Locale LOCALE_QQ_ZZ = new Locale("qq", "ZZ"); @Before public void setUp() throws Exception; @Test public void testConstructor(); private void assertValidToLocale(final String language); private void assertValidToLocale(final String localeString, final String language, final String country); private void assertValidToLocale( final String localeString, final String language, final String country, final String variant); @Test public void testToLocale_1Part(); @Test public void testToLocale_2Part(); @Test public void testToLocale_3Part(); private void assertLocaleLookupList(final Locale locale, final Locale defaultLocale, final Locale[] expected); @Test public void testLocaleLookupList_Locale(); @Test public void testLocaleLookupList_LocaleLocale(); @Test public void testAvailableLocaleList(); @Test public void testAvailableLocaleSet(); @SuppressWarnings("boxing") // JUnit4 does not support primitive equality testing apart from long @Test public void testIsAvailableLocale(); private void assertLanguageByCountry(final String country, final String[] languages); @Test public void testLanguagesByCountry(); private void assertCountriesByLanguage(final String language, final String[] countries); @Test public void testCountriesByLanguage(); private static void assertUnmodifiableCollection(final Collection<?> coll); @Test public void testLang328(); @Test public void testLang865(); @Test public void testParseAllLocales(); } ``` You are a professional Java test case writer, please create a test case named `testAvailableLocaleSet` for the `LocaleUtils` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test availableLocaleSet() method. */
348
// // Abstract Java Tested Class // package org.apache.commons.lang3; // // import java.util.ArrayList; // import java.util.Arrays; // import java.util.Collections; // import java.util.HashSet; // import java.util.List; // import java.util.Locale; // import java.util.Set; // import java.util.concurrent.ConcurrentHashMap; // import java.util.concurrent.ConcurrentMap; // // // // public class LocaleUtils { // private static final ConcurrentMap<String, List<Locale>> cLanguagesByCountry = // new ConcurrentHashMap<String, List<Locale>>(); // private static final ConcurrentMap<String, List<Locale>> cCountriesByLanguage = // new ConcurrentHashMap<String, List<Locale>>(); // // public LocaleUtils(); // public static Locale toLocale(final String str); // public static List<Locale> localeLookupList(final Locale locale); // public static List<Locale> localeLookupList(final Locale locale, final Locale defaultLocale); // public static List<Locale> availableLocaleList(); // public static Set<Locale> availableLocaleSet(); // public static boolean isAvailableLocale(final Locale locale); // public static List<Locale> languagesByCountry(final String countryCode); // public static List<Locale> countriesByLanguage(final String languageCode); // } // // // Abstract Java Test Class // package org.apache.commons.lang3; // // 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.assertSame; // import static org.junit.Assert.assertTrue; // import static org.junit.Assert.fail; // import java.lang.reflect.Constructor; // import java.lang.reflect.Modifier; // import java.util.Arrays; // import java.util.Collection; // import java.util.HashSet; // import java.util.Iterator; // import java.util.List; // import java.util.Locale; // import java.util.Set; // import org.junit.Before; // import org.junit.Test; // // // // public class LocaleUtilsTest { // private static final Locale LOCALE_EN = new Locale("en", ""); // private static final Locale LOCALE_EN_US = new Locale("en", "US"); // private static final Locale LOCALE_EN_US_ZZZZ = new Locale("en", "US", "ZZZZ"); // private static final Locale LOCALE_FR = new Locale("fr", ""); // private static final Locale LOCALE_FR_CA = new Locale("fr", "CA"); // private static final Locale LOCALE_QQ = new Locale("qq", ""); // private static final Locale LOCALE_QQ_ZZ = new Locale("qq", "ZZ"); // // @Before // public void setUp() throws Exception; // @Test // public void testConstructor(); // private void assertValidToLocale(final String language); // private void assertValidToLocale(final String localeString, final String language, final String country); // private void assertValidToLocale( // final String localeString, final String language, // final String country, final String variant); // @Test // public void testToLocale_1Part(); // @Test // public void testToLocale_2Part(); // @Test // public void testToLocale_3Part(); // private void assertLocaleLookupList(final Locale locale, final Locale defaultLocale, final Locale[] expected); // @Test // public void testLocaleLookupList_Locale(); // @Test // public void testLocaleLookupList_LocaleLocale(); // @Test // public void testAvailableLocaleList(); // @Test // public void testAvailableLocaleSet(); // @SuppressWarnings("boxing") // JUnit4 does not support primitive equality testing apart from long // @Test // public void testIsAvailableLocale(); // private void assertLanguageByCountry(final String country, final String[] languages); // @Test // public void testLanguagesByCountry(); // private void assertCountriesByLanguage(final String language, final String[] countries); // @Test // public void testCountriesByLanguage(); // private static void assertUnmodifiableCollection(final Collection<?> coll); // @Test // public void testLang328(); // @Test // public void testLang865(); // @Test // public void testParseAllLocales(); // } // You are a professional Java test case writer, please create a test case named `testAvailableLocaleSet` for the `LocaleUtils` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test availableLocaleSet() method. */ //----------------------------------------------------------------------- @Test public void testAvailableLocaleSet() {
/** * Test availableLocaleSet() method. */ //-----------------------------------------------------------------------
1
org.apache.commons.lang3.LocaleUtils
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.lang3; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class LocaleUtils { private static final ConcurrentMap<String, List<Locale>> cLanguagesByCountry = new ConcurrentHashMap<String, List<Locale>>(); private static final ConcurrentMap<String, List<Locale>> cCountriesByLanguage = new ConcurrentHashMap<String, List<Locale>>(); public LocaleUtils(); public static Locale toLocale(final String str); public static List<Locale> localeLookupList(final Locale locale); public static List<Locale> localeLookupList(final Locale locale, final Locale defaultLocale); public static List<Locale> availableLocaleList(); public static Set<Locale> availableLocaleSet(); public static boolean isAvailableLocale(final Locale locale); public static List<Locale> languagesByCountry(final String countryCode); public static List<Locale> countriesByLanguage(final String languageCode); } // Abstract Java Test Class package org.apache.commons.lang3; 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.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Set; import org.junit.Before; import org.junit.Test; public class LocaleUtilsTest { private static final Locale LOCALE_EN = new Locale("en", ""); private static final Locale LOCALE_EN_US = new Locale("en", "US"); private static final Locale LOCALE_EN_US_ZZZZ = new Locale("en", "US", "ZZZZ"); private static final Locale LOCALE_FR = new Locale("fr", ""); private static final Locale LOCALE_FR_CA = new Locale("fr", "CA"); private static final Locale LOCALE_QQ = new Locale("qq", ""); private static final Locale LOCALE_QQ_ZZ = new Locale("qq", "ZZ"); @Before public void setUp() throws Exception; @Test public void testConstructor(); private void assertValidToLocale(final String language); private void assertValidToLocale(final String localeString, final String language, final String country); private void assertValidToLocale( final String localeString, final String language, final String country, final String variant); @Test public void testToLocale_1Part(); @Test public void testToLocale_2Part(); @Test public void testToLocale_3Part(); private void assertLocaleLookupList(final Locale locale, final Locale defaultLocale, final Locale[] expected); @Test public void testLocaleLookupList_Locale(); @Test public void testLocaleLookupList_LocaleLocale(); @Test public void testAvailableLocaleList(); @Test public void testAvailableLocaleSet(); @SuppressWarnings("boxing") // JUnit4 does not support primitive equality testing apart from long @Test public void testIsAvailableLocale(); private void assertLanguageByCountry(final String country, final String[] languages); @Test public void testLanguagesByCountry(); private void assertCountriesByLanguage(final String language, final String[] countries); @Test public void testCountriesByLanguage(); private static void assertUnmodifiableCollection(final Collection<?> coll); @Test public void testLang328(); @Test public void testLang865(); @Test public void testParseAllLocales(); } ``` You are a professional Java test case writer, please create a test case named `testAvailableLocaleSet` for the `LocaleUtils` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test availableLocaleSet() method. */ //----------------------------------------------------------------------- @Test public void testAvailableLocaleSet() { ```
public class LocaleUtils
package org.apache.commons.lang3; 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.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Set; import org.junit.Before; import org.junit.Test;
@Before public void setUp() throws Exception; @Test public void testConstructor(); private void assertValidToLocale(final String language); private void assertValidToLocale(final String localeString, final String language, final String country); private void assertValidToLocale( final String localeString, final String language, final String country, final String variant); @Test public void testToLocale_1Part(); @Test public void testToLocale_2Part(); @Test public void testToLocale_3Part(); private void assertLocaleLookupList(final Locale locale, final Locale defaultLocale, final Locale[] expected); @Test public void testLocaleLookupList_Locale(); @Test public void testLocaleLookupList_LocaleLocale(); @Test public void testAvailableLocaleList(); @Test public void testAvailableLocaleSet(); @SuppressWarnings("boxing") // JUnit4 does not support primitive equality testing apart from long @Test public void testIsAvailableLocale(); private void assertLanguageByCountry(final String country, final String[] languages); @Test public void testLanguagesByCountry(); private void assertCountriesByLanguage(final String language, final String[] countries); @Test public void testCountriesByLanguage(); private static void assertUnmodifiableCollection(final Collection<?> coll); @Test public void testLang328(); @Test public void testLang865(); @Test public void testParseAllLocales();
3cde3d3816ae5a3b58e97c68f027e7ad040b24460d2eba97af5544c57a9b0a2a
[ "org.apache.commons.lang3.LocaleUtilsTest::testAvailableLocaleSet" ]
private static final ConcurrentMap<String, List<Locale>> cLanguagesByCountry = new ConcurrentHashMap<String, List<Locale>>(); private static final ConcurrentMap<String, List<Locale>> cCountriesByLanguage = new ConcurrentHashMap<String, List<Locale>>();
@Test public void testAvailableLocaleSet()
private static final Locale LOCALE_EN = new Locale("en", ""); private static final Locale LOCALE_EN_US = new Locale("en", "US"); private static final Locale LOCALE_EN_US_ZZZZ = new Locale("en", "US", "ZZZZ"); private static final Locale LOCALE_FR = new Locale("fr", ""); private static final Locale LOCALE_FR_CA = new Locale("fr", "CA"); private static final Locale LOCALE_QQ = new Locale("qq", ""); private static final Locale LOCALE_QQ_ZZ = new Locale("qq", "ZZ");
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; 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.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Set; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link LocaleUtils}. * * @version $Id$ */ public class LocaleUtilsTest { private static final Locale LOCALE_EN = new Locale("en", ""); private static final Locale LOCALE_EN_US = new Locale("en", "US"); private static final Locale LOCALE_EN_US_ZZZZ = new Locale("en", "US", "ZZZZ"); private static final Locale LOCALE_FR = new Locale("fr", ""); private static final Locale LOCALE_FR_CA = new Locale("fr", "CA"); private static final Locale LOCALE_QQ = new Locale("qq", ""); private static final Locale LOCALE_QQ_ZZ = new Locale("qq", "ZZ"); @Before public void setUp() throws Exception { // Testing #LANG-304. Must be called before availableLocaleSet is called. LocaleUtils.isAvailableLocale(Locale.getDefault()); } //----------------------------------------------------------------------- /** * Test that constructors are public, and work, etc. */ @Test public void testConstructor() { assertNotNull(new LocaleUtils()); final Constructor<?>[] cons = LocaleUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertTrue(Modifier.isPublic(cons[0].getModifiers())); assertTrue(Modifier.isPublic(LocaleUtils.class.getModifiers())); assertFalse(Modifier.isFinal(LocaleUtils.class.getModifiers())); } //----------------------------------------------------------------------- /** * Pass in a valid language, test toLocale. * * @param language the language string */ private void assertValidToLocale(final String language) { final Locale locale = LocaleUtils.toLocale(language); assertNotNull("valid locale", locale); assertEquals(language, locale.getLanguage()); //country and variant are empty assertTrue(locale.getCountry() == null || locale.getCountry().isEmpty()); assertTrue(locale.getVariant() == null || locale.getVariant().isEmpty()); } /** * Pass in a valid language, test toLocale. * * @param localeString to pass to toLocale() * @param language of the resulting Locale * @param country of the resulting Locale */ private void assertValidToLocale(final String localeString, final String language, final String country) { final Locale locale = LocaleUtils.toLocale(localeString); assertNotNull("valid locale", locale); assertEquals(language, locale.getLanguage()); assertEquals(country, locale.getCountry()); //variant is empty assertTrue(locale.getVariant() == null || locale.getVariant().isEmpty()); } /** * Pass in a valid language, test toLocale. * * @param localeString to pass to toLocale() * @param language of the resulting Locale * @param country of the resulting Locale * @param variant of the resulting Locale */ private void assertValidToLocale( final String localeString, final String language, final String country, final String variant) { final Locale locale = LocaleUtils.toLocale(localeString); assertNotNull("valid locale", locale); assertEquals(language, locale.getLanguage()); assertEquals(country, locale.getCountry()); assertEquals(variant, locale.getVariant()); } /** * Test toLocale() method. */ @Test public void testToLocale_1Part() { assertEquals(null, LocaleUtils.toLocale((String) null)); assertValidToLocale("us"); assertValidToLocale("fr"); assertValidToLocale("de"); assertValidToLocale("zh"); // Valid format but lang doesnt exist, should make instance anyway assertValidToLocale("qq"); try { LocaleUtils.toLocale("Us"); fail("Should fail if not lowercase"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("US"); fail("Should fail if not lowercase"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uS"); fail("Should fail if not lowercase"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("u#"); fail("Should fail if not lowercase"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("u"); fail("Must be 2 chars if less than 5"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uuu"); fail("Must be 2 chars if less than 5"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uu_U"); fail("Must be 2 chars if less than 5"); } catch (final IllegalArgumentException iae) {} } /** * Test toLocale() method. */ @Test public void testToLocale_2Part() { assertValidToLocale("us_EN", "us", "EN"); //valid though doesnt exist assertValidToLocale("us_ZH", "us", "ZH"); try { LocaleUtils.toLocale("us-EN"); fail("Should fail as not underscore"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("us_En"); fail("Should fail second part not uppercase"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("us_en"); fail("Should fail second part not uppercase"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("us_eN"); fail("Should fail second part not uppercase"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uS_EN"); fail("Should fail first part not lowercase"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("us_E3"); fail("Should fail second part not uppercase"); } catch (final IllegalArgumentException iae) {} } /** * Test toLocale() method. */ @Test public void testToLocale_3Part() { assertValidToLocale("us_EN_A", "us", "EN", "A"); // this isn't pretty, but was caused by a jdk bug it seems // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4210525 if (SystemUtils.isJavaVersionAtLeast(JAVA_1_4)) { assertValidToLocale("us_EN_a", "us", "EN", "a"); assertValidToLocale("us_EN_SFsafdFDsdfF", "us", "EN", "SFsafdFDsdfF"); } else { assertValidToLocale("us_EN_a", "us", "EN", "A"); assertValidToLocale("us_EN_SFsafdFDsdfF", "us", "EN", "SFSAFDFDSDFF"); } try { LocaleUtils.toLocale("us_EN-a"); fail("Should fail as not underscore"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uu_UU_"); fail("Must be 3, 5 or 7+ in length"); } catch (final IllegalArgumentException iae) {} } //----------------------------------------------------------------------- /** * Helper method for local lookups. * * @param locale the input locale * @param defaultLocale the input default locale * @param expected expected results */ private void assertLocaleLookupList(final Locale locale, final Locale defaultLocale, final Locale[] expected) { final List<Locale> localeList = defaultLocale == null ? LocaleUtils.localeLookupList(locale) : LocaleUtils.localeLookupList(locale, defaultLocale); assertEquals(expected.length, localeList.size()); assertEquals(Arrays.asList(expected), localeList); assertUnmodifiableCollection(localeList); } //----------------------------------------------------------------------- /** * Test localeLookupList() method. */ @Test public void testLocaleLookupList_Locale() { assertLocaleLookupList(null, null, new Locale[0]); assertLocaleLookupList(LOCALE_QQ, null, new Locale[]{LOCALE_QQ}); assertLocaleLookupList(LOCALE_EN, null, new Locale[]{LOCALE_EN}); assertLocaleLookupList(LOCALE_EN, null, new Locale[]{LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US, null, new Locale[] { LOCALE_EN_US, LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, null, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN}); } /** * Test localeLookupList() method. */ @Test public void testLocaleLookupList_LocaleLocale() { assertLocaleLookupList(LOCALE_QQ, LOCALE_QQ, new Locale[]{LOCALE_QQ}); assertLocaleLookupList(LOCALE_EN, LOCALE_EN, new Locale[]{LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US, LOCALE_EN_US, new Locale[]{ LOCALE_EN_US, LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US, LOCALE_QQ, new Locale[] { LOCALE_EN_US, LOCALE_EN, LOCALE_QQ}); assertLocaleLookupList(LOCALE_EN_US, LOCALE_QQ_ZZ, new Locale[] { LOCALE_EN_US, LOCALE_EN, LOCALE_QQ_ZZ}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, null, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_EN_US_ZZZZ, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_QQ, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN, LOCALE_QQ}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_QQ_ZZ, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN, LOCALE_QQ_ZZ}); assertLocaleLookupList(LOCALE_FR_CA, LOCALE_EN, new Locale[] { LOCALE_FR_CA, LOCALE_FR, LOCALE_EN}); } //----------------------------------------------------------------------- /** * Test availableLocaleList() method. */ @Test public void testAvailableLocaleList() { final List<Locale> list = LocaleUtils.availableLocaleList(); final List<Locale> list2 = LocaleUtils.availableLocaleList(); assertNotNull(list); assertSame(list, list2); assertUnmodifiableCollection(list); final Locale[] jdkLocaleArray = Locale.getAvailableLocales(); final List<Locale> jdkLocaleList = Arrays.asList(jdkLocaleArray); assertEquals(jdkLocaleList, list); } //----------------------------------------------------------------------- /** * Test availableLocaleSet() method. */ @Test public void testAvailableLocaleSet() { final Set<Locale> set = LocaleUtils.availableLocaleSet(); final Set<Locale> set2 = LocaleUtils.availableLocaleSet(); assertNotNull(set); assertSame(set, set2); assertUnmodifiableCollection(set); final Locale[] jdkLocaleArray = Locale.getAvailableLocales(); final List<Locale> jdkLocaleList = Arrays.asList(jdkLocaleArray); final Set<Locale> jdkLocaleSet = new HashSet<Locale>(jdkLocaleList); assertEquals(jdkLocaleSet, set); } //----------------------------------------------------------------------- /** * Test availableLocaleSet() method. */ @SuppressWarnings("boxing") // JUnit4 does not support primitive equality testing apart from long @Test public void testIsAvailableLocale() { final Set<Locale> set = LocaleUtils.availableLocaleSet(); assertEquals(set.contains(LOCALE_EN), LocaleUtils.isAvailableLocale(LOCALE_EN)); assertEquals(set.contains(LOCALE_EN_US), LocaleUtils.isAvailableLocale(LOCALE_EN_US)); assertEquals(set.contains(LOCALE_EN_US_ZZZZ), LocaleUtils.isAvailableLocale(LOCALE_EN_US_ZZZZ)); assertEquals(set.contains(LOCALE_FR), LocaleUtils.isAvailableLocale(LOCALE_FR)); assertEquals(set.contains(LOCALE_FR_CA), LocaleUtils.isAvailableLocale(LOCALE_FR_CA)); assertEquals(set.contains(LOCALE_QQ), LocaleUtils.isAvailableLocale(LOCALE_QQ)); assertEquals(set.contains(LOCALE_QQ_ZZ), LocaleUtils.isAvailableLocale(LOCALE_QQ_ZZ)); } //----------------------------------------------------------------------- /** * Make sure the language by country is correct. It checks that * the LocaleUtils.languagesByCountry(country) call contains the * array of languages passed in. It may contain more due to JVM * variations. * * @param country * @param languages array of languages that should be returned */ private void assertLanguageByCountry(final String country, final String[] languages) { final List<Locale> list = LocaleUtils.languagesByCountry(country); final List<Locale> list2 = LocaleUtils.languagesByCountry(country); assertNotNull(list); assertSame(list, list2); //search through langauges for (final String language : languages) { final Iterator<Locale> iterator = list.iterator(); boolean found = false; // see if it was returned by the set while (iterator.hasNext()) { final Locale locale = iterator.next(); // should have an en empty variant assertTrue(locale.getVariant() == null || locale.getVariant().isEmpty()); assertEquals(country, locale.getCountry()); if (language.equals(locale.getLanguage())) { found = true; break; } } if (!found) { fail("Cound not find language: " + language + " for country: " + country); } } assertUnmodifiableCollection(list); } /** * Test languagesByCountry() method. */ @Test public void testLanguagesByCountry() { assertLanguageByCountry(null, new String[0]); assertLanguageByCountry("GB", new String[]{"en"}); assertLanguageByCountry("ZZ", new String[0]); assertLanguageByCountry("CH", new String[]{"fr", "de", "it"}); } //----------------------------------------------------------------------- /** * Make sure the country by language is correct. It checks that * the LocaleUtils.countryByLanguage(language) call contains the * array of countries passed in. It may contain more due to JVM * variations. * * * @param language * @param countries array of countries that should be returned */ private void assertCountriesByLanguage(final String language, final String[] countries) { final List<Locale> list = LocaleUtils.countriesByLanguage(language); final List<Locale> list2 = LocaleUtils.countriesByLanguage(language); assertNotNull(list); assertSame(list, list2); //search through langauges for (final String countrie : countries) { final Iterator<Locale> iterator = list.iterator(); boolean found = false; // see if it was returned by the set while (iterator.hasNext()) { final Locale locale = iterator.next(); // should have an en empty variant assertTrue(locale.getVariant() == null || locale.getVariant().isEmpty()); assertEquals(language, locale.getLanguage()); if (countrie.equals(locale.getCountry())) { found = true; break; } } if (!found) { fail("Cound not find language: " + countrie + " for country: " + language); } } assertUnmodifiableCollection(list); } /** * Test countriesByLanguage() method. */ @Test public void testCountriesByLanguage() { assertCountriesByLanguage(null, new String[0]); assertCountriesByLanguage("de", new String[]{"DE", "CH", "AT", "LU"}); assertCountriesByLanguage("zz", new String[0]); assertCountriesByLanguage("it", new String[]{"IT", "CH"}); } /** * @param coll the collection to check */ private static void assertUnmodifiableCollection(final Collection<?> coll) { try { coll.add(null); fail(); } catch (final UnsupportedOperationException ex) {} } /** * Tests #LANG-328 - only language+variant */ @Test public void testLang328() { assertValidToLocale("fr__P", "fr", "", "P"); assertValidToLocale("fr__POSIX", "fr", "", "POSIX"); } /** * Tests #LANG-865, strings starting with an underscore. */ @Test public void testLang865() { assertValidToLocale("_GB", "", "GB", ""); assertValidToLocale("_GB_P", "", "GB", "P"); assertValidToLocale("_GB_POSIX", "", "GB", "POSIX"); try { LocaleUtils.toLocale("_G"); fail("Must be at least 3 chars if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_Gb"); fail("Must be uppercase if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_gB"); fail("Must be uppercase if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_1B"); fail("Must be letter if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_G1"); fail("Must be letter if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_GB_"); fail("Must be at least 5 chars if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_GBAP"); fail("Must have underscore after the country if starts with underscore and is at least 5 chars"); } catch (final IllegalArgumentException iae) { } } @Test public void testParseAllLocales() {} // Defects4J: flaky method // @Test // public void testParseAllLocales() { // Locale[] locales = Locale.getAvailableLocales(); // int failures = 0; // for (Locale l : locales) { // // Check if it's possible to recreate the Locale using just the standard constructor // Locale locale = new Locale(l.getLanguage(), l.getCountry(), l.getVariant()); // if (l.equals(locale)) { // it is possible for LocaleUtils.toLocale to handle these Locales // String str = l.toString(); // // Look for the script/extension suffix // int suff = str.indexOf("_#"); // if (suff == - 1) { // suff = str.indexOf("#"); // } // if (suff >= 0) { // we have a suffix // try { // LocaleUtils.toLocale(str); // shouuld cause IAE // System.out.println("Should not have parsed: " + str); // failures++; // continue; // try next Locale // } catch (IllegalArgumentException iae) { // // expected; try without suffix // str = str.substring(0, suff); // } // } // Locale loc = LocaleUtils.toLocale(str); // if (!l.equals(loc)) { // System.out.println("Failed to parse: " + str); // failures++; // } // } // } // if (failures > 0) { // fail("Failed "+failures+" test(s)"); // } // } }
[ { "be_test_class_file": "org/apache/commons/lang3/LocaleUtils.java", "be_test_class_name": "org.apache.commons.lang3.LocaleUtils", "be_test_function_name": "availableLocaleList", "be_test_function_signature": "()Ljava/util/List;", "line_numbers": [ "216" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/LocaleUtils.java", "be_test_class_name": "org.apache.commons.lang3.LocaleUtils", "be_test_function_name": "availableLocaleSet", "be_test_function_signature": "()Ljava/util/Set;", "line_numbers": [ "230" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/LocaleUtils.java", "be_test_class_name": "org.apache.commons.lang3.LocaleUtils", "be_test_function_name": "isAvailableLocale", "be_test_function_signature": "(Ljava/util/Locale;)Z", "line_numbers": [ "241" ], "method_line_rate": 1 } ]
public class DateAxisTests extends TestCase
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()); }
// 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 `testPreviousStandardDateHourB` 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 6 hours (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);
913
testPreviousStandardDateHourB
```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 `testPreviousStandardDateHourB` 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 6 hours (just for the sake of having a multiple). */
846
// 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 `testPreviousStandardDateHourB` 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 6 hours (just for the sake of having a multiple). */ public void testPreviousStandardDateHourB() {
/** * A basic check for the testPreviousStandardDate() method when the * tick unit is 6 hours (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 `testPreviousStandardDateHourB` 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 6 hours (just for the sake of having a multiple). */ public void testPreviousStandardDateHourB() { ```
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);
3f7248025a9a73f48577694f0a1106b85457446457d73570cbd9c203127d3664
[ "org.jfree.chart.axis.junit.DateAxisTests::testPreviousStandardDateHourB" ]
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 testPreviousStandardDateHourB()
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.22580645161290322 }, { "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 TestUnsupportedDateTimeField extends TestCase
public void testMethodsThatShouldAlwaysReturnNull() { DateTimeField fieldOne = UnsupportedDateTimeField.getInstance( dateTimeFieldTypeOne, UnsupportedDurationField .getInstance(weeks)); assertNull(fieldOne.getLeapDurationField()); assertNull(fieldOne.getRangeDurationField()); }
// // 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 `testMethodsThatShouldAlwaysReturnNull` for the `UnsupportedDateTimeField` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * According to the JavaDocs, there are two methods that should always * return null. * getRangeDurationField() * getLeapDurationField() * * Ensure that these are in fact null. */
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();
142
testMethodsThatShouldAlwaysReturnNull
```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 `testMethodsThatShouldAlwaysReturnNull` for the `UnsupportedDateTimeField` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * According to the JavaDocs, there are two methods that should always * return null. * getRangeDurationField() * getLeapDurationField() * * Ensure that these are in fact null. */
135
// // 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 `testMethodsThatShouldAlwaysReturnNull` for the `UnsupportedDateTimeField` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * 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() {
/** * According to the JavaDocs, there are two methods that should always * return null. * getRangeDurationField() * getLeapDurationField() * * Ensure that these are in fact null. */
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 `testMethodsThatShouldAlwaysReturnNull` for the `UnsupportedDateTimeField` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * 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() { ```
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();
43574150aa7148738872674a3119217cb6ba3d3d3f597542813990170d0a8bfd
[ "org.joda.time.field.TestUnsupportedDateTimeField::testMethodsThatShouldAlwaysReturnNull" ]
private static final long serialVersionUID = -1934618396111902255L; private static HashMap<DateTimeFieldType, UnsupportedDateTimeField> cCache; private final DateTimeFieldType iType; private final DurationField iDurationField;
public void testMethodsThatShouldAlwaysReturnNull()
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": "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": 0.7 }, { "be_test_class_file": "org/joda/time/field/UnsupportedDateTimeField.java", "be_test_class_name": "org.joda.time.field.UnsupportedDateTimeField", "be_test_function_name": "getLeapDurationField", "be_test_function_signature": "()Lorg/joda/time/DurationField;", "line_numbers": [ "379" ], "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": "getRangeDurationField", "be_test_function_signature": "()Lorg/joda/time/DurationField;", "line_numbers": [ "352" ], "method_line_rate": 1 } ]
public class DateAxisTests extends TestCase
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()); }
// 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 `testPreviousStandardDateYearB` 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 years (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);
475
testPreviousStandardDateYearB
```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 `testPreviousStandardDateYearB` 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 years (just for the sake of having a multiple). */
408
// 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 `testPreviousStandardDateYearB` 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 years (just for the sake of having a multiple). */ public void testPreviousStandardDateYearB() {
/** * A basic check for the testPreviousStandardDate() method when the * tick unit is 10 years (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 `testPreviousStandardDateYearB` 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 years (just for the sake of having a multiple). */ public void testPreviousStandardDateYearB() { ```
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);
4541c57a40feadb2fb093169566e918480e1a1c79beb501a9c76afe971a25e40
[ "org.jfree.chart.axis.junit.DateAxisTests::testPreviousStandardDateYearB" ]
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 testPreviousStandardDateYearB()
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.20967741935483872 }, { "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 LocaleUtilsTest
@Test public void testLocaleLookupList_Locale() { assertLocaleLookupList(null, null, new Locale[0]); assertLocaleLookupList(LOCALE_QQ, null, new Locale[]{LOCALE_QQ}); assertLocaleLookupList(LOCALE_EN, null, new Locale[]{LOCALE_EN}); assertLocaleLookupList(LOCALE_EN, null, new Locale[]{LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US, null, new Locale[] { LOCALE_EN_US, LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, null, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN}); }
// // Abstract Java Tested Class // package org.apache.commons.lang3; // // import java.util.ArrayList; // import java.util.Arrays; // import java.util.Collections; // import java.util.HashSet; // import java.util.List; // import java.util.Locale; // import java.util.Set; // import java.util.concurrent.ConcurrentHashMap; // import java.util.concurrent.ConcurrentMap; // // // // public class LocaleUtils { // private static final ConcurrentMap<String, List<Locale>> cLanguagesByCountry = // new ConcurrentHashMap<String, List<Locale>>(); // private static final ConcurrentMap<String, List<Locale>> cCountriesByLanguage = // new ConcurrentHashMap<String, List<Locale>>(); // // public LocaleUtils(); // public static Locale toLocale(final String str); // public static List<Locale> localeLookupList(final Locale locale); // public static List<Locale> localeLookupList(final Locale locale, final Locale defaultLocale); // public static List<Locale> availableLocaleList(); // public static Set<Locale> availableLocaleSet(); // public static boolean isAvailableLocale(final Locale locale); // public static List<Locale> languagesByCountry(final String countryCode); // public static List<Locale> countriesByLanguage(final String languageCode); // } // // // Abstract Java Test Class // package org.apache.commons.lang3; // // 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.assertSame; // import static org.junit.Assert.assertTrue; // import static org.junit.Assert.fail; // import java.lang.reflect.Constructor; // import java.lang.reflect.Modifier; // import java.util.Arrays; // import java.util.Collection; // import java.util.HashSet; // import java.util.Iterator; // import java.util.List; // import java.util.Locale; // import java.util.Set; // import org.junit.Before; // import org.junit.Test; // // // // public class LocaleUtilsTest { // private static final Locale LOCALE_EN = new Locale("en", ""); // private static final Locale LOCALE_EN_US = new Locale("en", "US"); // private static final Locale LOCALE_EN_US_ZZZZ = new Locale("en", "US", "ZZZZ"); // private static final Locale LOCALE_FR = new Locale("fr", ""); // private static final Locale LOCALE_FR_CA = new Locale("fr", "CA"); // private static final Locale LOCALE_QQ = new Locale("qq", ""); // private static final Locale LOCALE_QQ_ZZ = new Locale("qq", "ZZ"); // // @Before // public void setUp() throws Exception; // @Test // public void testConstructor(); // private void assertValidToLocale(final String language); // private void assertValidToLocale(final String localeString, final String language, final String country); // private void assertValidToLocale( // final String localeString, final String language, // final String country, final String variant); // @Test // public void testToLocale_1Part(); // @Test // public void testToLocale_2Part(); // @Test // public void testToLocale_3Part(); // private void assertLocaleLookupList(final Locale locale, final Locale defaultLocale, final Locale[] expected); // @Test // public void testLocaleLookupList_Locale(); // @Test // public void testLocaleLookupList_LocaleLocale(); // @Test // public void testAvailableLocaleList(); // @Test // public void testAvailableLocaleSet(); // @SuppressWarnings("boxing") // JUnit4 does not support primitive equality testing apart from long // @Test // public void testIsAvailableLocale(); // private void assertLanguageByCountry(final String country, final String[] languages); // @Test // public void testLanguagesByCountry(); // private void assertCountriesByLanguage(final String language, final String[] countries); // @Test // public void testCountriesByLanguage(); // private static void assertUnmodifiableCollection(final Collection<?> coll); // @Test // public void testLang328(); // @Test // public void testLang865(); // @Test // public void testParseAllLocales(); // } // You are a professional Java test case writer, please create a test case named `testLocaleLookupList_Locale` for the `LocaleUtils` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test localeLookupList() method. */
src/test/java/org/apache/commons/lang3/LocaleUtilsTest.java
package org.apache.commons.lang3; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap;
public LocaleUtils(); public static Locale toLocale(final String str); public static List<Locale> localeLookupList(final Locale locale); public static List<Locale> localeLookupList(final Locale locale, final Locale defaultLocale); public static List<Locale> availableLocaleList(); public static Set<Locale> availableLocaleSet(); public static boolean isAvailableLocale(final Locale locale); public static List<Locale> languagesByCountry(final String countryCode); public static List<Locale> countriesByLanguage(final String languageCode);
271
testLocaleLookupList_Locale
```java // Abstract Java Tested Class package org.apache.commons.lang3; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class LocaleUtils { private static final ConcurrentMap<String, List<Locale>> cLanguagesByCountry = new ConcurrentHashMap<String, List<Locale>>(); private static final ConcurrentMap<String, List<Locale>> cCountriesByLanguage = new ConcurrentHashMap<String, List<Locale>>(); public LocaleUtils(); public static Locale toLocale(final String str); public static List<Locale> localeLookupList(final Locale locale); public static List<Locale> localeLookupList(final Locale locale, final Locale defaultLocale); public static List<Locale> availableLocaleList(); public static Set<Locale> availableLocaleSet(); public static boolean isAvailableLocale(final Locale locale); public static List<Locale> languagesByCountry(final String countryCode); public static List<Locale> countriesByLanguage(final String languageCode); } // Abstract Java Test Class package org.apache.commons.lang3; 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.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Set; import org.junit.Before; import org.junit.Test; public class LocaleUtilsTest { private static final Locale LOCALE_EN = new Locale("en", ""); private static final Locale LOCALE_EN_US = new Locale("en", "US"); private static final Locale LOCALE_EN_US_ZZZZ = new Locale("en", "US", "ZZZZ"); private static final Locale LOCALE_FR = new Locale("fr", ""); private static final Locale LOCALE_FR_CA = new Locale("fr", "CA"); private static final Locale LOCALE_QQ = new Locale("qq", ""); private static final Locale LOCALE_QQ_ZZ = new Locale("qq", "ZZ"); @Before public void setUp() throws Exception; @Test public void testConstructor(); private void assertValidToLocale(final String language); private void assertValidToLocale(final String localeString, final String language, final String country); private void assertValidToLocale( final String localeString, final String language, final String country, final String variant); @Test public void testToLocale_1Part(); @Test public void testToLocale_2Part(); @Test public void testToLocale_3Part(); private void assertLocaleLookupList(final Locale locale, final Locale defaultLocale, final Locale[] expected); @Test public void testLocaleLookupList_Locale(); @Test public void testLocaleLookupList_LocaleLocale(); @Test public void testAvailableLocaleList(); @Test public void testAvailableLocaleSet(); @SuppressWarnings("boxing") // JUnit4 does not support primitive equality testing apart from long @Test public void testIsAvailableLocale(); private void assertLanguageByCountry(final String country, final String[] languages); @Test public void testLanguagesByCountry(); private void assertCountriesByLanguage(final String language, final String[] countries); @Test public void testCountriesByLanguage(); private static void assertUnmodifiableCollection(final Collection<?> coll); @Test public void testLang328(); @Test public void testLang865(); @Test public void testParseAllLocales(); } ``` You are a professional Java test case writer, please create a test case named `testLocaleLookupList_Locale` for the `LocaleUtils` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test localeLookupList() method. */
256
// // Abstract Java Tested Class // package org.apache.commons.lang3; // // import java.util.ArrayList; // import java.util.Arrays; // import java.util.Collections; // import java.util.HashSet; // import java.util.List; // import java.util.Locale; // import java.util.Set; // import java.util.concurrent.ConcurrentHashMap; // import java.util.concurrent.ConcurrentMap; // // // // public class LocaleUtils { // private static final ConcurrentMap<String, List<Locale>> cLanguagesByCountry = // new ConcurrentHashMap<String, List<Locale>>(); // private static final ConcurrentMap<String, List<Locale>> cCountriesByLanguage = // new ConcurrentHashMap<String, List<Locale>>(); // // public LocaleUtils(); // public static Locale toLocale(final String str); // public static List<Locale> localeLookupList(final Locale locale); // public static List<Locale> localeLookupList(final Locale locale, final Locale defaultLocale); // public static List<Locale> availableLocaleList(); // public static Set<Locale> availableLocaleSet(); // public static boolean isAvailableLocale(final Locale locale); // public static List<Locale> languagesByCountry(final String countryCode); // public static List<Locale> countriesByLanguage(final String languageCode); // } // // // Abstract Java Test Class // package org.apache.commons.lang3; // // 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.assertSame; // import static org.junit.Assert.assertTrue; // import static org.junit.Assert.fail; // import java.lang.reflect.Constructor; // import java.lang.reflect.Modifier; // import java.util.Arrays; // import java.util.Collection; // import java.util.HashSet; // import java.util.Iterator; // import java.util.List; // import java.util.Locale; // import java.util.Set; // import org.junit.Before; // import org.junit.Test; // // // // public class LocaleUtilsTest { // private static final Locale LOCALE_EN = new Locale("en", ""); // private static final Locale LOCALE_EN_US = new Locale("en", "US"); // private static final Locale LOCALE_EN_US_ZZZZ = new Locale("en", "US", "ZZZZ"); // private static final Locale LOCALE_FR = new Locale("fr", ""); // private static final Locale LOCALE_FR_CA = new Locale("fr", "CA"); // private static final Locale LOCALE_QQ = new Locale("qq", ""); // private static final Locale LOCALE_QQ_ZZ = new Locale("qq", "ZZ"); // // @Before // public void setUp() throws Exception; // @Test // public void testConstructor(); // private void assertValidToLocale(final String language); // private void assertValidToLocale(final String localeString, final String language, final String country); // private void assertValidToLocale( // final String localeString, final String language, // final String country, final String variant); // @Test // public void testToLocale_1Part(); // @Test // public void testToLocale_2Part(); // @Test // public void testToLocale_3Part(); // private void assertLocaleLookupList(final Locale locale, final Locale defaultLocale, final Locale[] expected); // @Test // public void testLocaleLookupList_Locale(); // @Test // public void testLocaleLookupList_LocaleLocale(); // @Test // public void testAvailableLocaleList(); // @Test // public void testAvailableLocaleSet(); // @SuppressWarnings("boxing") // JUnit4 does not support primitive equality testing apart from long // @Test // public void testIsAvailableLocale(); // private void assertLanguageByCountry(final String country, final String[] languages); // @Test // public void testLanguagesByCountry(); // private void assertCountriesByLanguage(final String language, final String[] countries); // @Test // public void testCountriesByLanguage(); // private static void assertUnmodifiableCollection(final Collection<?> coll); // @Test // public void testLang328(); // @Test // public void testLang865(); // @Test // public void testParseAllLocales(); // } // You are a professional Java test case writer, please create a test case named `testLocaleLookupList_Locale` for the `LocaleUtils` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test localeLookupList() method. */ //----------------------------------------------------------------------- @Test public void testLocaleLookupList_Locale() {
/** * Test localeLookupList() method. */ //-----------------------------------------------------------------------
1
org.apache.commons.lang3.LocaleUtils
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.lang3; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class LocaleUtils { private static final ConcurrentMap<String, List<Locale>> cLanguagesByCountry = new ConcurrentHashMap<String, List<Locale>>(); private static final ConcurrentMap<String, List<Locale>> cCountriesByLanguage = new ConcurrentHashMap<String, List<Locale>>(); public LocaleUtils(); public static Locale toLocale(final String str); public static List<Locale> localeLookupList(final Locale locale); public static List<Locale> localeLookupList(final Locale locale, final Locale defaultLocale); public static List<Locale> availableLocaleList(); public static Set<Locale> availableLocaleSet(); public static boolean isAvailableLocale(final Locale locale); public static List<Locale> languagesByCountry(final String countryCode); public static List<Locale> countriesByLanguage(final String languageCode); } // Abstract Java Test Class package org.apache.commons.lang3; 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.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Set; import org.junit.Before; import org.junit.Test; public class LocaleUtilsTest { private static final Locale LOCALE_EN = new Locale("en", ""); private static final Locale LOCALE_EN_US = new Locale("en", "US"); private static final Locale LOCALE_EN_US_ZZZZ = new Locale("en", "US", "ZZZZ"); private static final Locale LOCALE_FR = new Locale("fr", ""); private static final Locale LOCALE_FR_CA = new Locale("fr", "CA"); private static final Locale LOCALE_QQ = new Locale("qq", ""); private static final Locale LOCALE_QQ_ZZ = new Locale("qq", "ZZ"); @Before public void setUp() throws Exception; @Test public void testConstructor(); private void assertValidToLocale(final String language); private void assertValidToLocale(final String localeString, final String language, final String country); private void assertValidToLocale( final String localeString, final String language, final String country, final String variant); @Test public void testToLocale_1Part(); @Test public void testToLocale_2Part(); @Test public void testToLocale_3Part(); private void assertLocaleLookupList(final Locale locale, final Locale defaultLocale, final Locale[] expected); @Test public void testLocaleLookupList_Locale(); @Test public void testLocaleLookupList_LocaleLocale(); @Test public void testAvailableLocaleList(); @Test public void testAvailableLocaleSet(); @SuppressWarnings("boxing") // JUnit4 does not support primitive equality testing apart from long @Test public void testIsAvailableLocale(); private void assertLanguageByCountry(final String country, final String[] languages); @Test public void testLanguagesByCountry(); private void assertCountriesByLanguage(final String language, final String[] countries); @Test public void testCountriesByLanguage(); private static void assertUnmodifiableCollection(final Collection<?> coll); @Test public void testLang328(); @Test public void testLang865(); @Test public void testParseAllLocales(); } ``` You are a professional Java test case writer, please create a test case named `testLocaleLookupList_Locale` for the `LocaleUtils` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test localeLookupList() method. */ //----------------------------------------------------------------------- @Test public void testLocaleLookupList_Locale() { ```
public class LocaleUtils
package org.apache.commons.lang3; 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.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Set; import org.junit.Before; import org.junit.Test;
@Before public void setUp() throws Exception; @Test public void testConstructor(); private void assertValidToLocale(final String language); private void assertValidToLocale(final String localeString, final String language, final String country); private void assertValidToLocale( final String localeString, final String language, final String country, final String variant); @Test public void testToLocale_1Part(); @Test public void testToLocale_2Part(); @Test public void testToLocale_3Part(); private void assertLocaleLookupList(final Locale locale, final Locale defaultLocale, final Locale[] expected); @Test public void testLocaleLookupList_Locale(); @Test public void testLocaleLookupList_LocaleLocale(); @Test public void testAvailableLocaleList(); @Test public void testAvailableLocaleSet(); @SuppressWarnings("boxing") // JUnit4 does not support primitive equality testing apart from long @Test public void testIsAvailableLocale(); private void assertLanguageByCountry(final String country, final String[] languages); @Test public void testLanguagesByCountry(); private void assertCountriesByLanguage(final String language, final String[] countries); @Test public void testCountriesByLanguage(); private static void assertUnmodifiableCollection(final Collection<?> coll); @Test public void testLang328(); @Test public void testLang865(); @Test public void testParseAllLocales();
46cce23973f57409c26cf471b3e57aee275d61ff0a506c5911179f8656633d2d
[ "org.apache.commons.lang3.LocaleUtilsTest::testLocaleLookupList_Locale" ]
private static final ConcurrentMap<String, List<Locale>> cLanguagesByCountry = new ConcurrentHashMap<String, List<Locale>>(); private static final ConcurrentMap<String, List<Locale>> cCountriesByLanguage = new ConcurrentHashMap<String, List<Locale>>();
@Test public void testLocaleLookupList_Locale()
private static final Locale LOCALE_EN = new Locale("en", ""); private static final Locale LOCALE_EN_US = new Locale("en", "US"); private static final Locale LOCALE_EN_US_ZZZZ = new Locale("en", "US", "ZZZZ"); private static final Locale LOCALE_FR = new Locale("fr", ""); private static final Locale LOCALE_FR_CA = new Locale("fr", "CA"); private static final Locale LOCALE_QQ = new Locale("qq", ""); private static final Locale LOCALE_QQ_ZZ = new Locale("qq", "ZZ");
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; 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.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Set; import org.junit.Before; import org.junit.Test; /** * Unit tests for {@link LocaleUtils}. * * @version $Id$ */ public class LocaleUtilsTest { private static final Locale LOCALE_EN = new Locale("en", ""); private static final Locale LOCALE_EN_US = new Locale("en", "US"); private static final Locale LOCALE_EN_US_ZZZZ = new Locale("en", "US", "ZZZZ"); private static final Locale LOCALE_FR = new Locale("fr", ""); private static final Locale LOCALE_FR_CA = new Locale("fr", "CA"); private static final Locale LOCALE_QQ = new Locale("qq", ""); private static final Locale LOCALE_QQ_ZZ = new Locale("qq", "ZZ"); @Before public void setUp() throws Exception { // Testing #LANG-304. Must be called before availableLocaleSet is called. LocaleUtils.isAvailableLocale(Locale.getDefault()); } //----------------------------------------------------------------------- /** * Test that constructors are public, and work, etc. */ @Test public void testConstructor() { assertNotNull(new LocaleUtils()); final Constructor<?>[] cons = LocaleUtils.class.getDeclaredConstructors(); assertEquals(1, cons.length); assertTrue(Modifier.isPublic(cons[0].getModifiers())); assertTrue(Modifier.isPublic(LocaleUtils.class.getModifiers())); assertFalse(Modifier.isFinal(LocaleUtils.class.getModifiers())); } //----------------------------------------------------------------------- /** * Pass in a valid language, test toLocale. * * @param language the language string */ private void assertValidToLocale(final String language) { final Locale locale = LocaleUtils.toLocale(language); assertNotNull("valid locale", locale); assertEquals(language, locale.getLanguage()); //country and variant are empty assertTrue(locale.getCountry() == null || locale.getCountry().isEmpty()); assertTrue(locale.getVariant() == null || locale.getVariant().isEmpty()); } /** * Pass in a valid language, test toLocale. * * @param localeString to pass to toLocale() * @param language of the resulting Locale * @param country of the resulting Locale */ private void assertValidToLocale(final String localeString, final String language, final String country) { final Locale locale = LocaleUtils.toLocale(localeString); assertNotNull("valid locale", locale); assertEquals(language, locale.getLanguage()); assertEquals(country, locale.getCountry()); //variant is empty assertTrue(locale.getVariant() == null || locale.getVariant().isEmpty()); } /** * Pass in a valid language, test toLocale. * * @param localeString to pass to toLocale() * @param language of the resulting Locale * @param country of the resulting Locale * @param variant of the resulting Locale */ private void assertValidToLocale( final String localeString, final String language, final String country, final String variant) { final Locale locale = LocaleUtils.toLocale(localeString); assertNotNull("valid locale", locale); assertEquals(language, locale.getLanguage()); assertEquals(country, locale.getCountry()); assertEquals(variant, locale.getVariant()); } /** * Test toLocale() method. */ @Test public void testToLocale_1Part() { assertEquals(null, LocaleUtils.toLocale((String) null)); assertValidToLocale("us"); assertValidToLocale("fr"); assertValidToLocale("de"); assertValidToLocale("zh"); // Valid format but lang doesnt exist, should make instance anyway assertValidToLocale("qq"); try { LocaleUtils.toLocale("Us"); fail("Should fail if not lowercase"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("US"); fail("Should fail if not lowercase"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uS"); fail("Should fail if not lowercase"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("u#"); fail("Should fail if not lowercase"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("u"); fail("Must be 2 chars if less than 5"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uuu"); fail("Must be 2 chars if less than 5"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uu_U"); fail("Must be 2 chars if less than 5"); } catch (final IllegalArgumentException iae) {} } /** * Test toLocale() method. */ @Test public void testToLocale_2Part() { assertValidToLocale("us_EN", "us", "EN"); //valid though doesnt exist assertValidToLocale("us_ZH", "us", "ZH"); try { LocaleUtils.toLocale("us-EN"); fail("Should fail as not underscore"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("us_En"); fail("Should fail second part not uppercase"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("us_en"); fail("Should fail second part not uppercase"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("us_eN"); fail("Should fail second part not uppercase"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uS_EN"); fail("Should fail first part not lowercase"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("us_E3"); fail("Should fail second part not uppercase"); } catch (final IllegalArgumentException iae) {} } /** * Test toLocale() method. */ @Test public void testToLocale_3Part() { assertValidToLocale("us_EN_A", "us", "EN", "A"); // this isn't pretty, but was caused by a jdk bug it seems // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4210525 if (SystemUtils.isJavaVersionAtLeast(JAVA_1_4)) { assertValidToLocale("us_EN_a", "us", "EN", "a"); assertValidToLocale("us_EN_SFsafdFDsdfF", "us", "EN", "SFsafdFDsdfF"); } else { assertValidToLocale("us_EN_a", "us", "EN", "A"); assertValidToLocale("us_EN_SFsafdFDsdfF", "us", "EN", "SFSAFDFDSDFF"); } try { LocaleUtils.toLocale("us_EN-a"); fail("Should fail as not underscore"); } catch (final IllegalArgumentException iae) {} try { LocaleUtils.toLocale("uu_UU_"); fail("Must be 3, 5 or 7+ in length"); } catch (final IllegalArgumentException iae) {} } //----------------------------------------------------------------------- /** * Helper method for local lookups. * * @param locale the input locale * @param defaultLocale the input default locale * @param expected expected results */ private void assertLocaleLookupList(final Locale locale, final Locale defaultLocale, final Locale[] expected) { final List<Locale> localeList = defaultLocale == null ? LocaleUtils.localeLookupList(locale) : LocaleUtils.localeLookupList(locale, defaultLocale); assertEquals(expected.length, localeList.size()); assertEquals(Arrays.asList(expected), localeList); assertUnmodifiableCollection(localeList); } //----------------------------------------------------------------------- /** * Test localeLookupList() method. */ @Test public void testLocaleLookupList_Locale() { assertLocaleLookupList(null, null, new Locale[0]); assertLocaleLookupList(LOCALE_QQ, null, new Locale[]{LOCALE_QQ}); assertLocaleLookupList(LOCALE_EN, null, new Locale[]{LOCALE_EN}); assertLocaleLookupList(LOCALE_EN, null, new Locale[]{LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US, null, new Locale[] { LOCALE_EN_US, LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, null, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN}); } /** * Test localeLookupList() method. */ @Test public void testLocaleLookupList_LocaleLocale() { assertLocaleLookupList(LOCALE_QQ, LOCALE_QQ, new Locale[]{LOCALE_QQ}); assertLocaleLookupList(LOCALE_EN, LOCALE_EN, new Locale[]{LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US, LOCALE_EN_US, new Locale[]{ LOCALE_EN_US, LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US, LOCALE_QQ, new Locale[] { LOCALE_EN_US, LOCALE_EN, LOCALE_QQ}); assertLocaleLookupList(LOCALE_EN_US, LOCALE_QQ_ZZ, new Locale[] { LOCALE_EN_US, LOCALE_EN, LOCALE_QQ_ZZ}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, null, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_EN_US_ZZZZ, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_QQ, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN, LOCALE_QQ}); assertLocaleLookupList(LOCALE_EN_US_ZZZZ, LOCALE_QQ_ZZ, new Locale[] { LOCALE_EN_US_ZZZZ, LOCALE_EN_US, LOCALE_EN, LOCALE_QQ_ZZ}); assertLocaleLookupList(LOCALE_FR_CA, LOCALE_EN, new Locale[] { LOCALE_FR_CA, LOCALE_FR, LOCALE_EN}); } //----------------------------------------------------------------------- /** * Test availableLocaleList() method. */ @Test public void testAvailableLocaleList() { final List<Locale> list = LocaleUtils.availableLocaleList(); final List<Locale> list2 = LocaleUtils.availableLocaleList(); assertNotNull(list); assertSame(list, list2); assertUnmodifiableCollection(list); final Locale[] jdkLocaleArray = Locale.getAvailableLocales(); final List<Locale> jdkLocaleList = Arrays.asList(jdkLocaleArray); assertEquals(jdkLocaleList, list); } //----------------------------------------------------------------------- /** * Test availableLocaleSet() method. */ @Test public void testAvailableLocaleSet() { final Set<Locale> set = LocaleUtils.availableLocaleSet(); final Set<Locale> set2 = LocaleUtils.availableLocaleSet(); assertNotNull(set); assertSame(set, set2); assertUnmodifiableCollection(set); final Locale[] jdkLocaleArray = Locale.getAvailableLocales(); final List<Locale> jdkLocaleList = Arrays.asList(jdkLocaleArray); final Set<Locale> jdkLocaleSet = new HashSet<Locale>(jdkLocaleList); assertEquals(jdkLocaleSet, set); } //----------------------------------------------------------------------- /** * Test availableLocaleSet() method. */ @SuppressWarnings("boxing") // JUnit4 does not support primitive equality testing apart from long @Test public void testIsAvailableLocale() { final Set<Locale> set = LocaleUtils.availableLocaleSet(); assertEquals(set.contains(LOCALE_EN), LocaleUtils.isAvailableLocale(LOCALE_EN)); assertEquals(set.contains(LOCALE_EN_US), LocaleUtils.isAvailableLocale(LOCALE_EN_US)); assertEquals(set.contains(LOCALE_EN_US_ZZZZ), LocaleUtils.isAvailableLocale(LOCALE_EN_US_ZZZZ)); assertEquals(set.contains(LOCALE_FR), LocaleUtils.isAvailableLocale(LOCALE_FR)); assertEquals(set.contains(LOCALE_FR_CA), LocaleUtils.isAvailableLocale(LOCALE_FR_CA)); assertEquals(set.contains(LOCALE_QQ), LocaleUtils.isAvailableLocale(LOCALE_QQ)); assertEquals(set.contains(LOCALE_QQ_ZZ), LocaleUtils.isAvailableLocale(LOCALE_QQ_ZZ)); } //----------------------------------------------------------------------- /** * Make sure the language by country is correct. It checks that * the LocaleUtils.languagesByCountry(country) call contains the * array of languages passed in. It may contain more due to JVM * variations. * * @param country * @param languages array of languages that should be returned */ private void assertLanguageByCountry(final String country, final String[] languages) { final List<Locale> list = LocaleUtils.languagesByCountry(country); final List<Locale> list2 = LocaleUtils.languagesByCountry(country); assertNotNull(list); assertSame(list, list2); //search through langauges for (final String language : languages) { final Iterator<Locale> iterator = list.iterator(); boolean found = false; // see if it was returned by the set while (iterator.hasNext()) { final Locale locale = iterator.next(); // should have an en empty variant assertTrue(locale.getVariant() == null || locale.getVariant().isEmpty()); assertEquals(country, locale.getCountry()); if (language.equals(locale.getLanguage())) { found = true; break; } } if (!found) { fail("Cound not find language: " + language + " for country: " + country); } } assertUnmodifiableCollection(list); } /** * Test languagesByCountry() method. */ @Test public void testLanguagesByCountry() { assertLanguageByCountry(null, new String[0]); assertLanguageByCountry("GB", new String[]{"en"}); assertLanguageByCountry("ZZ", new String[0]); assertLanguageByCountry("CH", new String[]{"fr", "de", "it"}); } //----------------------------------------------------------------------- /** * Make sure the country by language is correct. It checks that * the LocaleUtils.countryByLanguage(language) call contains the * array of countries passed in. It may contain more due to JVM * variations. * * * @param language * @param countries array of countries that should be returned */ private void assertCountriesByLanguage(final String language, final String[] countries) { final List<Locale> list = LocaleUtils.countriesByLanguage(language); final List<Locale> list2 = LocaleUtils.countriesByLanguage(language); assertNotNull(list); assertSame(list, list2); //search through langauges for (final String countrie : countries) { final Iterator<Locale> iterator = list.iterator(); boolean found = false; // see if it was returned by the set while (iterator.hasNext()) { final Locale locale = iterator.next(); // should have an en empty variant assertTrue(locale.getVariant() == null || locale.getVariant().isEmpty()); assertEquals(language, locale.getLanguage()); if (countrie.equals(locale.getCountry())) { found = true; break; } } if (!found) { fail("Cound not find language: " + countrie + " for country: " + language); } } assertUnmodifiableCollection(list); } /** * Test countriesByLanguage() method. */ @Test public void testCountriesByLanguage() { assertCountriesByLanguage(null, new String[0]); assertCountriesByLanguage("de", new String[]{"DE", "CH", "AT", "LU"}); assertCountriesByLanguage("zz", new String[0]); assertCountriesByLanguage("it", new String[]{"IT", "CH"}); } /** * @param coll the collection to check */ private static void assertUnmodifiableCollection(final Collection<?> coll) { try { coll.add(null); fail(); } catch (final UnsupportedOperationException ex) {} } /** * Tests #LANG-328 - only language+variant */ @Test public void testLang328() { assertValidToLocale("fr__P", "fr", "", "P"); assertValidToLocale("fr__POSIX", "fr", "", "POSIX"); } /** * Tests #LANG-865, strings starting with an underscore. */ @Test public void testLang865() { assertValidToLocale("_GB", "", "GB", ""); assertValidToLocale("_GB_P", "", "GB", "P"); assertValidToLocale("_GB_POSIX", "", "GB", "POSIX"); try { LocaleUtils.toLocale("_G"); fail("Must be at least 3 chars if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_Gb"); fail("Must be uppercase if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_gB"); fail("Must be uppercase if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_1B"); fail("Must be letter if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_G1"); fail("Must be letter if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_GB_"); fail("Must be at least 5 chars if starts with underscore"); } catch (final IllegalArgumentException iae) { } try { LocaleUtils.toLocale("_GBAP"); fail("Must have underscore after the country if starts with underscore and is at least 5 chars"); } catch (final IllegalArgumentException iae) { } } @Test public void testParseAllLocales() {} // Defects4J: flaky method // @Test // public void testParseAllLocales() { // Locale[] locales = Locale.getAvailableLocales(); // int failures = 0; // for (Locale l : locales) { // // Check if it's possible to recreate the Locale using just the standard constructor // Locale locale = new Locale(l.getLanguage(), l.getCountry(), l.getVariant()); // if (l.equals(locale)) { // it is possible for LocaleUtils.toLocale to handle these Locales // String str = l.toString(); // // Look for the script/extension suffix // int suff = str.indexOf("_#"); // if (suff == - 1) { // suff = str.indexOf("#"); // } // if (suff >= 0) { // we have a suffix // try { // LocaleUtils.toLocale(str); // shouuld cause IAE // System.out.println("Should not have parsed: " + str); // failures++; // continue; // try next Locale // } catch (IllegalArgumentException iae) { // // expected; try without suffix // str = str.substring(0, suff); // } // } // Locale loc = LocaleUtils.toLocale(str); // if (!l.equals(loc)) { // System.out.println("Failed to parse: " + str); // failures++; // } // } // } // if (failures > 0) { // fail("Failed "+failures+" test(s)"); // } // } }
[ { "be_test_class_file": "org/apache/commons/lang3/LocaleUtils.java", "be_test_class_name": "org.apache.commons.lang3.LocaleUtils", "be_test_function_name": "availableLocaleList", "be_test_function_signature": "()Ljava/util/List;", "line_numbers": [ "216" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/LocaleUtils.java", "be_test_class_name": "org.apache.commons.lang3.LocaleUtils", "be_test_function_name": "isAvailableLocale", "be_test_function_signature": "(Ljava/util/Locale;)Z", "line_numbers": [ "241" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/LocaleUtils.java", "be_test_class_name": "org.apache.commons.lang3.LocaleUtils", "be_test_function_name": "localeLookupList", "be_test_function_signature": "(Ljava/util/Locale;)Ljava/util/List;", "line_numbers": [ "167" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/lang3/LocaleUtils.java", "be_test_class_name": "org.apache.commons.lang3.LocaleUtils", "be_test_function_name": "localeLookupList", "be_test_function_signature": "(Ljava/util/Locale;Ljava/util/Locale;)Ljava/util/List;", "line_numbers": [ "189", "190", "191", "192", "193", "195", "196", "198", "199", "202" ], "method_line_rate": 0.9 } ]
public class ConcurrentUtilsTest
@Test public void testPutIfAbsentKeyPresent() { final String key = "testKey"; final Integer value = 42; final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<String, Integer>(); map.put(key, value); assertEquals("Wrong result", value, ConcurrentUtils.putIfAbsent(map, key, 0)); assertEquals("Wrong value in map", value, map.get(key)); }
// // Abstract Java Tested Class // package org.apache.commons.lang3.concurrent; // // import java.util.concurrent.ConcurrentMap; // import java.util.concurrent.ExecutionException; // import java.util.concurrent.Future; // import java.util.concurrent.TimeUnit; // // // // public class ConcurrentUtils { // // // private ConcurrentUtils(); // public static ConcurrentException extractCause(final ExecutionException ex); // public static ConcurrentRuntimeException extractCauseUnchecked( // final ExecutionException ex); // public static void handleCause(final ExecutionException ex) // throws ConcurrentException; // public static void handleCauseUnchecked(final ExecutionException ex); // static Throwable checkedException(final Throwable ex); // private static void throwCause(final ExecutionException ex); // public static <T> T initialize(final ConcurrentInitializer<T> initializer) // throws ConcurrentException; // public static <T> T initializeUnchecked(final ConcurrentInitializer<T> initializer); // public static <K, V> V putIfAbsent(final ConcurrentMap<K, V> map, final K key, final V value); // public static <K, V> V createIfAbsent(final ConcurrentMap<K, V> map, final K key, // final ConcurrentInitializer<V> init) throws ConcurrentException; // public static <K, V> V createIfAbsentUnchecked(final ConcurrentMap<K, V> map, // final K key, final ConcurrentInitializer<V> init); // public static <T> Future<T> constantFuture(final T value); // ConstantFuture(final T value); // @Override // public boolean isDone(); // @Override // public T get(); // @Override // public T get(final long timeout, final TimeUnit unit); // @Override // public boolean isCancelled(); // @Override // public boolean cancel(final boolean mayInterruptIfRunning); // } // // // 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.assertSame; // import static org.junit.Assert.assertTrue; // import static org.junit.Assert.fail; // import java.util.concurrent.ConcurrentHashMap; // import java.util.concurrent.ConcurrentMap; // import java.util.concurrent.ExecutionException; // import java.util.concurrent.Future; // import java.util.concurrent.TimeUnit; // import org.easymock.EasyMock; // import org.junit.Test; // // // // public class ConcurrentUtilsTest { // // // @Test(expected = IllegalArgumentException.class) // public void testConcurrentExceptionCauseUnchecked(); // @Test(expected = IllegalArgumentException.class) // public void testConcurrentExceptionCauseError(); // @Test(expected = IllegalArgumentException.class) // public void testConcurrentExceptionCauseNull(); // @Test(expected = IllegalArgumentException.class) // public void testConcurrentRuntimeExceptionCauseUnchecked(); // @Test(expected = IllegalArgumentException.class) // public void testConcurrentRuntimeExceptionCauseError(); // @Test(expected = IllegalArgumentException.class) // public void testConcurrentRuntimeExceptionCauseNull(); // @Test // public void testExtractCauseNull(); // @Test // public void testExtractCauseNullCause(); // @Test // public void testExtractCauseError(); // @Test // public void testExtractCauseUncheckedException(); // @Test // public void testExtractCauseChecked(); // @Test // public void testExtractCauseUncheckedNull(); // @Test // public void testExtractCauseUncheckedNullCause(); // @Test // public void testExtractCauseUncheckedError(); // @Test // public void testExtractCauseUncheckedUncheckedException(); // @Test // public void testExtractCauseUncheckedChecked(); // @Test // public void testHandleCauseError() throws ConcurrentException; // @Test // public void testHandleCauseUncheckedException() throws ConcurrentException; // @Test // public void testHandleCauseChecked(); // @Test // public void testHandleCauseNull() throws ConcurrentException; // @Test // public void testHandleCauseUncheckedError(); // @Test // public void testHandleCauseUncheckedUncheckedException(); // @Test // public void testHandleCauseUncheckedChecked(); // @Test // public void testHandleCauseUncheckedNull(); // @Test // public void testInitializeNull() throws ConcurrentException; // @Test // public void testInitialize() throws ConcurrentException; // @Test // public void testInitializeUncheckedNull(); // @Test // public void testInitializeUnchecked() throws ConcurrentException; // @Test // public void testInitializeUncheckedEx() throws ConcurrentException; // @Test // public void testConstantFuture_Integer() throws Exception; // @Test // public void testConstantFuture_null() throws Exception; // @Test // public void testPutIfAbsentKeyPresent(); // @Test // public void testPutIfAbsentKeyNotPresent(); // @Test // public void testPutIfAbsentNullMap(); // @Test // public void testCreateIfAbsentKeyPresent() throws ConcurrentException; // @Test // public void testCreateIfAbsentKeyNotPresent() throws ConcurrentException; // @Test // public void testCreateIfAbsentNullMap() throws ConcurrentException; // @Test // public void testCreateIfAbsentNullInit() throws ConcurrentException; // @Test // public void testCreateIfAbsentUncheckedSuccess(); // @Test // public void testCreateIfAbsentUncheckedException() // throws ConcurrentException; // } // You are a professional Java test case writer, please create a test case named `testPutIfAbsentKeyPresent` for the `ConcurrentUtils` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests putIfAbsent() if the map contains the key in question. */
src/test/java/org/apache/commons/lang3/concurrent/ConcurrentUtilsTest.java
package org.apache.commons.lang3.concurrent; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit;
private ConcurrentUtils(); public static ConcurrentException extractCause(final ExecutionException ex); public static ConcurrentRuntimeException extractCauseUnchecked( final ExecutionException ex); public static void handleCause(final ExecutionException ex) throws ConcurrentException; public static void handleCauseUnchecked(final ExecutionException ex); static Throwable checkedException(final Throwable ex); private static void throwCause(final ExecutionException ex); public static <T> T initialize(final ConcurrentInitializer<T> initializer) throws ConcurrentException; public static <T> T initializeUnchecked(final ConcurrentInitializer<T> initializer); public static <K, V> V putIfAbsent(final ConcurrentMap<K, V> map, final K key, final V value); public static <K, V> V createIfAbsent(final ConcurrentMap<K, V> map, final K key, final ConcurrentInitializer<V> init) throws ConcurrentException; public static <K, V> V createIfAbsentUnchecked(final ConcurrentMap<K, V> map, final K key, final ConcurrentInitializer<V> init); public static <T> Future<T> constantFuture(final T value); ConstantFuture(final T value); @Override public boolean isDone(); @Override public T get(); @Override public T get(final long timeout, final TimeUnit unit); @Override public boolean isCancelled(); @Override public boolean cancel(final boolean mayInterruptIfRunning);
425
testPutIfAbsentKeyPresent
```java // Abstract Java Tested Class package org.apache.commons.lang3.concurrent; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; public class ConcurrentUtils { private ConcurrentUtils(); public static ConcurrentException extractCause(final ExecutionException ex); public static ConcurrentRuntimeException extractCauseUnchecked( final ExecutionException ex); public static void handleCause(final ExecutionException ex) throws ConcurrentException; public static void handleCauseUnchecked(final ExecutionException ex); static Throwable checkedException(final Throwable ex); private static void throwCause(final ExecutionException ex); public static <T> T initialize(final ConcurrentInitializer<T> initializer) throws ConcurrentException; public static <T> T initializeUnchecked(final ConcurrentInitializer<T> initializer); public static <K, V> V putIfAbsent(final ConcurrentMap<K, V> map, final K key, final V value); public static <K, V> V createIfAbsent(final ConcurrentMap<K, V> map, final K key, final ConcurrentInitializer<V> init) throws ConcurrentException; public static <K, V> V createIfAbsentUnchecked(final ConcurrentMap<K, V> map, final K key, final ConcurrentInitializer<V> init); public static <T> Future<T> constantFuture(final T value); ConstantFuture(final T value); @Override public boolean isDone(); @Override public T get(); @Override public T get(final long timeout, final TimeUnit unit); @Override public boolean isCancelled(); @Override public boolean cancel(final boolean mayInterruptIfRunning); } // 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.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.easymock.EasyMock; import org.junit.Test; public class ConcurrentUtilsTest { @Test(expected = IllegalArgumentException.class) public void testConcurrentExceptionCauseUnchecked(); @Test(expected = IllegalArgumentException.class) public void testConcurrentExceptionCauseError(); @Test(expected = IllegalArgumentException.class) public void testConcurrentExceptionCauseNull(); @Test(expected = IllegalArgumentException.class) public void testConcurrentRuntimeExceptionCauseUnchecked(); @Test(expected = IllegalArgumentException.class) public void testConcurrentRuntimeExceptionCauseError(); @Test(expected = IllegalArgumentException.class) public void testConcurrentRuntimeExceptionCauseNull(); @Test public void testExtractCauseNull(); @Test public void testExtractCauseNullCause(); @Test public void testExtractCauseError(); @Test public void testExtractCauseUncheckedException(); @Test public void testExtractCauseChecked(); @Test public void testExtractCauseUncheckedNull(); @Test public void testExtractCauseUncheckedNullCause(); @Test public void testExtractCauseUncheckedError(); @Test public void testExtractCauseUncheckedUncheckedException(); @Test public void testExtractCauseUncheckedChecked(); @Test public void testHandleCauseError() throws ConcurrentException; @Test public void testHandleCauseUncheckedException() throws ConcurrentException; @Test public void testHandleCauseChecked(); @Test public void testHandleCauseNull() throws ConcurrentException; @Test public void testHandleCauseUncheckedError(); @Test public void testHandleCauseUncheckedUncheckedException(); @Test public void testHandleCauseUncheckedChecked(); @Test public void testHandleCauseUncheckedNull(); @Test public void testInitializeNull() throws ConcurrentException; @Test public void testInitialize() throws ConcurrentException; @Test public void testInitializeUncheckedNull(); @Test public void testInitializeUnchecked() throws ConcurrentException; @Test public void testInitializeUncheckedEx() throws ConcurrentException; @Test public void testConstantFuture_Integer() throws Exception; @Test public void testConstantFuture_null() throws Exception; @Test public void testPutIfAbsentKeyPresent(); @Test public void testPutIfAbsentKeyNotPresent(); @Test public void testPutIfAbsentNullMap(); @Test public void testCreateIfAbsentKeyPresent() throws ConcurrentException; @Test public void testCreateIfAbsentKeyNotPresent() throws ConcurrentException; @Test public void testCreateIfAbsentNullMap() throws ConcurrentException; @Test public void testCreateIfAbsentNullInit() throws ConcurrentException; @Test public void testCreateIfAbsentUncheckedSuccess(); @Test public void testCreateIfAbsentUncheckedException() throws ConcurrentException; } ``` You are a professional Java test case writer, please create a test case named `testPutIfAbsentKeyPresent` for the `ConcurrentUtils` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests putIfAbsent() if the map contains the key in question. */
416
// // Abstract Java Tested Class // package org.apache.commons.lang3.concurrent; // // import java.util.concurrent.ConcurrentMap; // import java.util.concurrent.ExecutionException; // import java.util.concurrent.Future; // import java.util.concurrent.TimeUnit; // // // // public class ConcurrentUtils { // // // private ConcurrentUtils(); // public static ConcurrentException extractCause(final ExecutionException ex); // public static ConcurrentRuntimeException extractCauseUnchecked( // final ExecutionException ex); // public static void handleCause(final ExecutionException ex) // throws ConcurrentException; // public static void handleCauseUnchecked(final ExecutionException ex); // static Throwable checkedException(final Throwable ex); // private static void throwCause(final ExecutionException ex); // public static <T> T initialize(final ConcurrentInitializer<T> initializer) // throws ConcurrentException; // public static <T> T initializeUnchecked(final ConcurrentInitializer<T> initializer); // public static <K, V> V putIfAbsent(final ConcurrentMap<K, V> map, final K key, final V value); // public static <K, V> V createIfAbsent(final ConcurrentMap<K, V> map, final K key, // final ConcurrentInitializer<V> init) throws ConcurrentException; // public static <K, V> V createIfAbsentUnchecked(final ConcurrentMap<K, V> map, // final K key, final ConcurrentInitializer<V> init); // public static <T> Future<T> constantFuture(final T value); // ConstantFuture(final T value); // @Override // public boolean isDone(); // @Override // public T get(); // @Override // public T get(final long timeout, final TimeUnit unit); // @Override // public boolean isCancelled(); // @Override // public boolean cancel(final boolean mayInterruptIfRunning); // } // // // 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.assertSame; // import static org.junit.Assert.assertTrue; // import static org.junit.Assert.fail; // import java.util.concurrent.ConcurrentHashMap; // import java.util.concurrent.ConcurrentMap; // import java.util.concurrent.ExecutionException; // import java.util.concurrent.Future; // import java.util.concurrent.TimeUnit; // import org.easymock.EasyMock; // import org.junit.Test; // // // // public class ConcurrentUtilsTest { // // // @Test(expected = IllegalArgumentException.class) // public void testConcurrentExceptionCauseUnchecked(); // @Test(expected = IllegalArgumentException.class) // public void testConcurrentExceptionCauseError(); // @Test(expected = IllegalArgumentException.class) // public void testConcurrentExceptionCauseNull(); // @Test(expected = IllegalArgumentException.class) // public void testConcurrentRuntimeExceptionCauseUnchecked(); // @Test(expected = IllegalArgumentException.class) // public void testConcurrentRuntimeExceptionCauseError(); // @Test(expected = IllegalArgumentException.class) // public void testConcurrentRuntimeExceptionCauseNull(); // @Test // public void testExtractCauseNull(); // @Test // public void testExtractCauseNullCause(); // @Test // public void testExtractCauseError(); // @Test // public void testExtractCauseUncheckedException(); // @Test // public void testExtractCauseChecked(); // @Test // public void testExtractCauseUncheckedNull(); // @Test // public void testExtractCauseUncheckedNullCause(); // @Test // public void testExtractCauseUncheckedError(); // @Test // public void testExtractCauseUncheckedUncheckedException(); // @Test // public void testExtractCauseUncheckedChecked(); // @Test // public void testHandleCauseError() throws ConcurrentException; // @Test // public void testHandleCauseUncheckedException() throws ConcurrentException; // @Test // public void testHandleCauseChecked(); // @Test // public void testHandleCauseNull() throws ConcurrentException; // @Test // public void testHandleCauseUncheckedError(); // @Test // public void testHandleCauseUncheckedUncheckedException(); // @Test // public void testHandleCauseUncheckedChecked(); // @Test // public void testHandleCauseUncheckedNull(); // @Test // public void testInitializeNull() throws ConcurrentException; // @Test // public void testInitialize() throws ConcurrentException; // @Test // public void testInitializeUncheckedNull(); // @Test // public void testInitializeUnchecked() throws ConcurrentException; // @Test // public void testInitializeUncheckedEx() throws ConcurrentException; // @Test // public void testConstantFuture_Integer() throws Exception; // @Test // public void testConstantFuture_null() throws Exception; // @Test // public void testPutIfAbsentKeyPresent(); // @Test // public void testPutIfAbsentKeyNotPresent(); // @Test // public void testPutIfAbsentNullMap(); // @Test // public void testCreateIfAbsentKeyPresent() throws ConcurrentException; // @Test // public void testCreateIfAbsentKeyNotPresent() throws ConcurrentException; // @Test // public void testCreateIfAbsentNullMap() throws ConcurrentException; // @Test // public void testCreateIfAbsentNullInit() throws ConcurrentException; // @Test // public void testCreateIfAbsentUncheckedSuccess(); // @Test // public void testCreateIfAbsentUncheckedException() // throws ConcurrentException; // } // You are a professional Java test case writer, please create a test case named `testPutIfAbsentKeyPresent` for the `ConcurrentUtils` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests putIfAbsent() if the map contains the key in question. */ //----------------------------------------------------------------------- @Test public void testPutIfAbsentKeyPresent() {
/** * Tests putIfAbsent() if the map contains the key in question. */ //-----------------------------------------------------------------------
1
org.apache.commons.lang3.concurrent.ConcurrentUtils
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.lang3.concurrent; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; public class ConcurrentUtils { private ConcurrentUtils(); public static ConcurrentException extractCause(final ExecutionException ex); public static ConcurrentRuntimeException extractCauseUnchecked( final ExecutionException ex); public static void handleCause(final ExecutionException ex) throws ConcurrentException; public static void handleCauseUnchecked(final ExecutionException ex); static Throwable checkedException(final Throwable ex); private static void throwCause(final ExecutionException ex); public static <T> T initialize(final ConcurrentInitializer<T> initializer) throws ConcurrentException; public static <T> T initializeUnchecked(final ConcurrentInitializer<T> initializer); public static <K, V> V putIfAbsent(final ConcurrentMap<K, V> map, final K key, final V value); public static <K, V> V createIfAbsent(final ConcurrentMap<K, V> map, final K key, final ConcurrentInitializer<V> init) throws ConcurrentException; public static <K, V> V createIfAbsentUnchecked(final ConcurrentMap<K, V> map, final K key, final ConcurrentInitializer<V> init); public static <T> Future<T> constantFuture(final T value); ConstantFuture(final T value); @Override public boolean isDone(); @Override public T get(); @Override public T get(final long timeout, final TimeUnit unit); @Override public boolean isCancelled(); @Override public boolean cancel(final boolean mayInterruptIfRunning); } // 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.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.easymock.EasyMock; import org.junit.Test; public class ConcurrentUtilsTest { @Test(expected = IllegalArgumentException.class) public void testConcurrentExceptionCauseUnchecked(); @Test(expected = IllegalArgumentException.class) public void testConcurrentExceptionCauseError(); @Test(expected = IllegalArgumentException.class) public void testConcurrentExceptionCauseNull(); @Test(expected = IllegalArgumentException.class) public void testConcurrentRuntimeExceptionCauseUnchecked(); @Test(expected = IllegalArgumentException.class) public void testConcurrentRuntimeExceptionCauseError(); @Test(expected = IllegalArgumentException.class) public void testConcurrentRuntimeExceptionCauseNull(); @Test public void testExtractCauseNull(); @Test public void testExtractCauseNullCause(); @Test public void testExtractCauseError(); @Test public void testExtractCauseUncheckedException(); @Test public void testExtractCauseChecked(); @Test public void testExtractCauseUncheckedNull(); @Test public void testExtractCauseUncheckedNullCause(); @Test public void testExtractCauseUncheckedError(); @Test public void testExtractCauseUncheckedUncheckedException(); @Test public void testExtractCauseUncheckedChecked(); @Test public void testHandleCauseError() throws ConcurrentException; @Test public void testHandleCauseUncheckedException() throws ConcurrentException; @Test public void testHandleCauseChecked(); @Test public void testHandleCauseNull() throws ConcurrentException; @Test public void testHandleCauseUncheckedError(); @Test public void testHandleCauseUncheckedUncheckedException(); @Test public void testHandleCauseUncheckedChecked(); @Test public void testHandleCauseUncheckedNull(); @Test public void testInitializeNull() throws ConcurrentException; @Test public void testInitialize() throws ConcurrentException; @Test public void testInitializeUncheckedNull(); @Test public void testInitializeUnchecked() throws ConcurrentException; @Test public void testInitializeUncheckedEx() throws ConcurrentException; @Test public void testConstantFuture_Integer() throws Exception; @Test public void testConstantFuture_null() throws Exception; @Test public void testPutIfAbsentKeyPresent(); @Test public void testPutIfAbsentKeyNotPresent(); @Test public void testPutIfAbsentNullMap(); @Test public void testCreateIfAbsentKeyPresent() throws ConcurrentException; @Test public void testCreateIfAbsentKeyNotPresent() throws ConcurrentException; @Test public void testCreateIfAbsentNullMap() throws ConcurrentException; @Test public void testCreateIfAbsentNullInit() throws ConcurrentException; @Test public void testCreateIfAbsentUncheckedSuccess(); @Test public void testCreateIfAbsentUncheckedException() throws ConcurrentException; } ``` You are a professional Java test case writer, please create a test case named `testPutIfAbsentKeyPresent` for the `ConcurrentUtils` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests putIfAbsent() if the map contains the key in question. */ //----------------------------------------------------------------------- @Test public void testPutIfAbsentKeyPresent() { ```
public class ConcurrentUtils
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.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.easymock.EasyMock; import org.junit.Test;
@Test(expected = IllegalArgumentException.class) public void testConcurrentExceptionCauseUnchecked(); @Test(expected = IllegalArgumentException.class) public void testConcurrentExceptionCauseError(); @Test(expected = IllegalArgumentException.class) public void testConcurrentExceptionCauseNull(); @Test(expected = IllegalArgumentException.class) public void testConcurrentRuntimeExceptionCauseUnchecked(); @Test(expected = IllegalArgumentException.class) public void testConcurrentRuntimeExceptionCauseError(); @Test(expected = IllegalArgumentException.class) public void testConcurrentRuntimeExceptionCauseNull(); @Test public void testExtractCauseNull(); @Test public void testExtractCauseNullCause(); @Test public void testExtractCauseError(); @Test public void testExtractCauseUncheckedException(); @Test public void testExtractCauseChecked(); @Test public void testExtractCauseUncheckedNull(); @Test public void testExtractCauseUncheckedNullCause(); @Test public void testExtractCauseUncheckedError(); @Test public void testExtractCauseUncheckedUncheckedException(); @Test public void testExtractCauseUncheckedChecked(); @Test public void testHandleCauseError() throws ConcurrentException; @Test public void testHandleCauseUncheckedException() throws ConcurrentException; @Test public void testHandleCauseChecked(); @Test public void testHandleCauseNull() throws ConcurrentException; @Test public void testHandleCauseUncheckedError(); @Test public void testHandleCauseUncheckedUncheckedException(); @Test public void testHandleCauseUncheckedChecked(); @Test public void testHandleCauseUncheckedNull(); @Test public void testInitializeNull() throws ConcurrentException; @Test public void testInitialize() throws ConcurrentException; @Test public void testInitializeUncheckedNull(); @Test public void testInitializeUnchecked() throws ConcurrentException; @Test public void testInitializeUncheckedEx() throws ConcurrentException; @Test public void testConstantFuture_Integer() throws Exception; @Test public void testConstantFuture_null() throws Exception; @Test public void testPutIfAbsentKeyPresent(); @Test public void testPutIfAbsentKeyNotPresent(); @Test public void testPutIfAbsentNullMap(); @Test public void testCreateIfAbsentKeyPresent() throws ConcurrentException; @Test public void testCreateIfAbsentKeyNotPresent() throws ConcurrentException; @Test public void testCreateIfAbsentNullMap() throws ConcurrentException; @Test public void testCreateIfAbsentNullInit() throws ConcurrentException; @Test public void testCreateIfAbsentUncheckedSuccess(); @Test public void testCreateIfAbsentUncheckedException() throws ConcurrentException;
4a09a349d10689b3b54c165956a271c89e4433636cdbae0841dbb320843bb145
[ "org.apache.commons.lang3.concurrent.ConcurrentUtilsTest::testPutIfAbsentKeyPresent" ]
@Test public void testPutIfAbsentKeyPresent()
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.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.easymock.EasyMock; import org.junit.Test; /** * Test class for {@link ConcurrentUtils}. * * @version $Id$ */ public class ConcurrentUtilsTest { /** * Tests creating a ConcurrentException with a runtime exception as cause. */ @Test(expected = IllegalArgumentException.class) public void testConcurrentExceptionCauseUnchecked() { new ConcurrentException(new RuntimeException()); } /** * Tests creating a ConcurrentException with an error as cause. */ @Test(expected = IllegalArgumentException.class) public void testConcurrentExceptionCauseError() { new ConcurrentException("An error", new Error()); } /** * Tests creating a ConcurrentException with null as cause. */ @Test(expected = IllegalArgumentException.class) public void testConcurrentExceptionCauseNull() { new ConcurrentException(null); } /** * Tries to create a ConcurrentRuntimeException with a runtime as cause. */ @Test(expected = IllegalArgumentException.class) public void testConcurrentRuntimeExceptionCauseUnchecked() { new ConcurrentRuntimeException(new RuntimeException()); } /** * Tries to create a ConcurrentRuntimeException with an error as cause. */ @Test(expected = IllegalArgumentException.class) public void testConcurrentRuntimeExceptionCauseError() { new ConcurrentRuntimeException("An error", new Error()); } /** * Tries to create a ConcurrentRuntimeException with null as cause. */ @Test(expected = IllegalArgumentException.class) public void testConcurrentRuntimeExceptionCauseNull() { new ConcurrentRuntimeException(null); } /** * Tests extractCause() for a null exception. */ @Test public void testExtractCauseNull() { assertNull("Non null result", ConcurrentUtils.extractCause(null)); } /** * Tests extractCause() if the cause of the passed in exception is null. */ @Test public void testExtractCauseNullCause() { assertNull("Non null result", ConcurrentUtils .extractCause(new ExecutionException("Test", null))); } /** * Tests extractCause() if the cause is an error. */ @Test public void testExtractCauseError() { final Error err = new AssertionError("Test"); try { ConcurrentUtils.extractCause(new ExecutionException(err)); fail("Error not thrown!"); } catch (final Error e) { assertEquals("Wrong error", err, e); } } /** * Tests extractCause() if the cause is an unchecked exception. */ @Test public void testExtractCauseUncheckedException() { final RuntimeException rex = new RuntimeException("Test"); try { ConcurrentUtils.extractCause(new ExecutionException(rex)); fail("Runtime exception not thrown!"); } catch (final RuntimeException r) { assertEquals("Wrong exception", rex, r); } } /** * Tests extractCause() if the cause is a checked exception. */ @Test public void testExtractCauseChecked() { final Exception ex = new Exception("Test"); final ConcurrentException cex = ConcurrentUtils .extractCause(new ExecutionException(ex)); assertSame("Wrong cause", ex, cex.getCause()); } /** * Tests extractCauseUnchecked() for a null exception. */ @Test public void testExtractCauseUncheckedNull() { assertNull("Non null result", ConcurrentUtils.extractCauseUnchecked(null)); } /** * Tests extractCauseUnchecked() if the cause of the passed in exception is null. */ @Test public void testExtractCauseUncheckedNullCause() { assertNull("Non null result", ConcurrentUtils .extractCauseUnchecked(new ExecutionException("Test", null))); } /** * Tests extractCauseUnchecked() if the cause is an error. */ @Test public void testExtractCauseUncheckedError() { final Error err = new AssertionError("Test"); try { ConcurrentUtils.extractCauseUnchecked(new ExecutionException(err)); fail("Error not thrown!"); } catch (final Error e) { assertEquals("Wrong error", err, e); } } /** * Tests extractCauseUnchecked() if the cause is an unchecked exception. */ @Test public void testExtractCauseUncheckedUncheckedException() { final RuntimeException rex = new RuntimeException("Test"); try { ConcurrentUtils.extractCauseUnchecked(new ExecutionException(rex)); fail("Runtime exception not thrown!"); } catch (final RuntimeException r) { assertEquals("Wrong exception", rex, r); } } /** * Tests extractCauseUnchecked() if the cause is a checked exception. */ @Test public void testExtractCauseUncheckedChecked() { final Exception ex = new Exception("Test"); final ConcurrentRuntimeException cex = ConcurrentUtils .extractCauseUnchecked(new ExecutionException(ex)); assertSame("Wrong cause", ex, cex.getCause()); } /** * Tests handleCause() if the cause is an error. */ @Test public void testHandleCauseError() throws ConcurrentException { final Error err = new AssertionError("Test"); try { ConcurrentUtils.handleCause(new ExecutionException(err)); fail("Error not thrown!"); } catch (final Error e) { assertEquals("Wrong error", err, e); } } /** * Tests handleCause() if the cause is an unchecked exception. */ @Test public void testHandleCauseUncheckedException() throws ConcurrentException { final RuntimeException rex = new RuntimeException("Test"); try { ConcurrentUtils.handleCause(new ExecutionException(rex)); fail("Runtime exception not thrown!"); } catch (final RuntimeException r) { assertEquals("Wrong exception", rex, r); } } /** * Tests handleCause() if the cause is a checked exception. */ @Test public void testHandleCauseChecked() { final Exception ex = new Exception("Test"); try { ConcurrentUtils.handleCause(new ExecutionException(ex)); fail("ConcurrentException not thrown!"); } catch (final ConcurrentException cex) { assertEquals("Wrong cause", ex, cex.getCause()); } } /** * Tests handleCause() for a null parameter or a null cause. In this case * the method should do nothing. We can only test that no exception is * thrown. */ @Test public void testHandleCauseNull() throws ConcurrentException { ConcurrentUtils.handleCause(null); ConcurrentUtils.handleCause(new ExecutionException("Test", null)); } /** * Tests handleCauseUnchecked() if the cause is an error. */ @Test public void testHandleCauseUncheckedError() { final Error err = new AssertionError("Test"); try { ConcurrentUtils.handleCauseUnchecked(new ExecutionException(err)); fail("Error not thrown!"); } catch (final Error e) { assertEquals("Wrong error", err, e); } } /** * Tests handleCauseUnchecked() if the cause is an unchecked exception. */ @Test public void testHandleCauseUncheckedUncheckedException() { final RuntimeException rex = new RuntimeException("Test"); try { ConcurrentUtils.handleCauseUnchecked(new ExecutionException(rex)); fail("Runtime exception not thrown!"); } catch (final RuntimeException r) { assertEquals("Wrong exception", rex, r); } } /** * Tests handleCauseUnchecked() if the cause is a checked exception. */ @Test public void testHandleCauseUncheckedChecked() { final Exception ex = new Exception("Test"); try { ConcurrentUtils.handleCauseUnchecked(new ExecutionException(ex)); fail("ConcurrentRuntimeException not thrown!"); } catch (final ConcurrentRuntimeException crex) { assertEquals("Wrong cause", ex, crex.getCause()); } } /** * Tests handleCauseUnchecked() for a null parameter or a null cause. In * this case the method should do nothing. We can only test that no * exception is thrown. */ @Test public void testHandleCauseUncheckedNull() { ConcurrentUtils.handleCauseUnchecked(null); ConcurrentUtils.handleCauseUnchecked(new ExecutionException("Test", null)); } //----------------------------------------------------------------------- /** * Tests initialize() for a null argument. */ @Test public void testInitializeNull() throws ConcurrentException { assertNull("Got a result", ConcurrentUtils.initialize(null)); } /** * Tests a successful initialize() operation. */ @Test public void testInitialize() throws ConcurrentException { @SuppressWarnings("unchecked") final ConcurrentInitializer<Object> init = EasyMock .createMock(ConcurrentInitializer.class); final Object result = new Object(); EasyMock.expect(init.get()).andReturn(result); EasyMock.replay(init); assertSame("Wrong result object", result, ConcurrentUtils .initialize(init)); EasyMock.verify(init); } /** * Tests initializeUnchecked() for a null argument. */ @Test public void testInitializeUncheckedNull() { assertNull("Got a result", ConcurrentUtils.initializeUnchecked(null)); } /** * Tests a successful initializeUnchecked() operation. */ @Test public void testInitializeUnchecked() throws ConcurrentException { @SuppressWarnings("unchecked") final ConcurrentInitializer<Object> init = EasyMock .createMock(ConcurrentInitializer.class); final Object result = new Object(); EasyMock.expect(init.get()).andReturn(result); EasyMock.replay(init); assertSame("Wrong result object", result, ConcurrentUtils .initializeUnchecked(init)); EasyMock.verify(init); } /** * Tests whether exceptions are correctly handled by initializeUnchecked(). */ @Test public void testInitializeUncheckedEx() throws ConcurrentException { @SuppressWarnings("unchecked") final ConcurrentInitializer<Object> init = EasyMock .createMock(ConcurrentInitializer.class); final Exception cause = new Exception(); EasyMock.expect(init.get()).andThrow(new ConcurrentException(cause)); EasyMock.replay(init); try { ConcurrentUtils.initializeUnchecked(init); fail("Exception not thrown!"); } catch (final ConcurrentRuntimeException crex) { assertSame("Wrong cause", cause, crex.getCause()); } EasyMock.verify(init); } //----------------------------------------------------------------------- /** * Tests constant future. */ @Test public void testConstantFuture_Integer() throws Exception { final Integer value = Integer.valueOf(5); final Future<Integer> test = ConcurrentUtils.constantFuture(value); assertTrue(test.isDone()); assertSame(value, test.get()); assertSame(value, test.get(1000, TimeUnit.SECONDS)); assertSame(value, test.get(1000, null)); assertFalse(test.isCancelled()); assertFalse(test.cancel(true)); assertFalse(test.cancel(false)); } /** * Tests constant future. */ @Test public void testConstantFuture_null() throws Exception { final Integer value = null; final Future<Integer> test = ConcurrentUtils.constantFuture(value); assertTrue(test.isDone()); assertSame(value, test.get()); assertSame(value, test.get(1000, TimeUnit.SECONDS)); assertSame(value, test.get(1000, null)); assertFalse(test.isCancelled()); assertFalse(test.cancel(true)); assertFalse(test.cancel(false)); } //----------------------------------------------------------------------- /** * Tests putIfAbsent() if the map contains the key in question. */ @Test public void testPutIfAbsentKeyPresent() { final String key = "testKey"; final Integer value = 42; final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<String, Integer>(); map.put(key, value); assertEquals("Wrong result", value, ConcurrentUtils.putIfAbsent(map, key, 0)); assertEquals("Wrong value in map", value, map.get(key)); } /** * Tests putIfAbsent() if the map does not contain the key in question. */ @Test public void testPutIfAbsentKeyNotPresent() { final String key = "testKey"; final Integer value = 42; final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<String, Integer>(); assertEquals("Wrong result", value, ConcurrentUtils.putIfAbsent(map, key, value)); assertEquals("Wrong value in map", value, map.get(key)); } /** * Tests putIfAbsent() if a null map is passed in. */ @Test public void testPutIfAbsentNullMap() { assertNull("Wrong result", ConcurrentUtils.putIfAbsent(null, "test", 100)); } /** * Tests createIfAbsent() if the key is found in the map. */ @Test public void testCreateIfAbsentKeyPresent() throws ConcurrentException { @SuppressWarnings("unchecked") final ConcurrentInitializer<Integer> init = EasyMock .createMock(ConcurrentInitializer.class); EasyMock.replay(init); final String key = "testKey"; final Integer value = 42; final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<String, Integer>(); map.put(key, value); assertEquals("Wrong result", value, ConcurrentUtils.createIfAbsent(map, key, init)); assertEquals("Wrong value in map", value, map.get(key)); EasyMock.verify(init); } /** * Tests createIfAbsent() if the map does not contain the key in question. */ @Test public void testCreateIfAbsentKeyNotPresent() throws ConcurrentException { @SuppressWarnings("unchecked") final ConcurrentInitializer<Integer> init = EasyMock .createMock(ConcurrentInitializer.class); final String key = "testKey"; final Integer value = 42; EasyMock.expect(init.get()).andReturn(value); EasyMock.replay(init); final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<String, Integer>(); assertEquals("Wrong result", value, ConcurrentUtils.createIfAbsent(map, key, init)); assertEquals("Wrong value in map", value, map.get(key)); EasyMock.verify(init); } /** * Tests createIfAbsent() if a null map is passed in. */ @Test public void testCreateIfAbsentNullMap() throws ConcurrentException { @SuppressWarnings("unchecked") final ConcurrentInitializer<Integer> init = EasyMock .createMock(ConcurrentInitializer.class); EasyMock.replay(init); assertNull("Wrong result", ConcurrentUtils.createIfAbsent(null, "test", init)); EasyMock.verify(init); } /** * Tests createIfAbsent() if a null initializer is passed in. */ @Test public void testCreateIfAbsentNullInit() throws ConcurrentException { final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<String, Integer>(); final String key = "testKey"; final Integer value = 42; map.put(key, value); assertNull("Wrong result", ConcurrentUtils.createIfAbsent(map, key, null)); assertEquals("Map was changed", value, map.get(key)); } /** * Tests createIfAbsentUnchecked() if no exception is thrown. */ @Test public void testCreateIfAbsentUncheckedSuccess() { final String key = "testKey"; final Integer value = 42; final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<String, Integer>(); assertEquals("Wrong result", value, ConcurrentUtils.createIfAbsentUnchecked(map, key, new ConstantInitializer<Integer>(value))); assertEquals("Wrong value in map", value, map.get(key)); } /** * Tests createIfAbsentUnchecked() if an exception is thrown. */ @Test public void testCreateIfAbsentUncheckedException() throws ConcurrentException { @SuppressWarnings("unchecked") final ConcurrentInitializer<Integer> init = EasyMock .createMock(ConcurrentInitializer.class); final Exception ex = new Exception(); EasyMock.expect(init.get()).andThrow(new ConcurrentException(ex)); EasyMock.replay(init); try { ConcurrentUtils.createIfAbsentUnchecked( new ConcurrentHashMap<String, Integer>(), "test", init); fail("Exception not thrown!"); } catch (final ConcurrentRuntimeException crex) { assertEquals("Wrong cause", ex, crex.getCause()); } EasyMock.verify(init); } }
[ { "be_test_class_file": "org/apache/commons/lang3/concurrent/ConcurrentUtils.java", "be_test_class_name": "org.apache.commons.lang3.concurrent.ConcurrentUtils", "be_test_function_name": "putIfAbsent", "be_test_function_signature": "(Ljava/util/concurrent/ConcurrentMap;Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", "line_numbers": [ "242", "243", "246", "247" ], "method_line_rate": 0.75 } ]
@RunWith(RetryRunner.class) public final class ValueServerTest
@Test public void testNextDigest() throws Exception { double next = 0.0; double tolerance = 0.1; vs.computeDistribution(); Assert.assertTrue("empirical distribution property", vs.getEmpiricalDistribution() != null); SummaryStatistics stats = new SummaryStatistics(); for (int i = 1; i < 1000; i++) { next = vs.getNext(); stats.addValue(next); } Assert.assertEquals("mean", 5.069831575018909, stats.getMean(), tolerance); Assert.assertEquals("std dev", 1.0173699343977738, stats.getStandardDeviation(), tolerance); vs.computeDistribution(500); stats = new SummaryStatistics(); for (int i = 1; i < 1000; i++) { next = vs.getNext(); stats.addValue(next); } Assert.assertEquals("mean", 5.069831575018909, stats.getMean(), tolerance); Assert.assertEquals("std dev", 1.0173699343977738, stats.getStandardDeviation(), tolerance); }
// // Abstract Java Tested Class // package org.apache.commons.math3.random; // // import java.io.BufferedReader; // import java.io.IOException; // import java.io.InputStreamReader; // import java.net.MalformedURLException; // import java.net.URL; // import org.apache.commons.math3.exception.MathIllegalArgumentException; // import org.apache.commons.math3.exception.MathIllegalStateException; // import org.apache.commons.math3.exception.NullArgumentException; // import org.apache.commons.math3.exception.ZeroException; // import org.apache.commons.math3.exception.util.LocalizedFormats; // // // // public class ValueServer { // public static final int DIGEST_MODE = 0; // public static final int REPLAY_MODE = 1; // public static final int UNIFORM_MODE = 2; // public static final int EXPONENTIAL_MODE = 3; // public static final int GAUSSIAN_MODE = 4; // public static final int CONSTANT_MODE = 5; // private int mode = 5; // private URL valuesFileURL = null; // private double mu = 0.0; // private double sigma = 0.0; // private EmpiricalDistribution empiricalDistribution = null; // private BufferedReader filePointer = null; // private final RandomDataImpl randomData; // // public ValueServer(); // @Deprecated // public ValueServer(RandomDataImpl randomData); // public ValueServer(RandomGenerator generator); // public double getNext() throws IOException, MathIllegalStateException, MathIllegalArgumentException; // public void fill(double[] values) // throws IOException, MathIllegalStateException, MathIllegalArgumentException; // public double[] fill(int length) // throws IOException, MathIllegalStateException, MathIllegalArgumentException; // public void computeDistribution() throws IOException, ZeroException, NullArgumentException; // public void computeDistribution(int binCount) throws NullArgumentException, IOException, ZeroException; // public int getMode(); // public void setMode(int mode); // public URL getValuesFileURL(); // public void setValuesFileURL(String url) throws MalformedURLException; // public void setValuesFileURL(URL url); // public EmpiricalDistribution getEmpiricalDistribution(); // public void resetReplayFile() throws IOException; // public void closeReplayFile() throws IOException; // public double getMu(); // public void setMu(double mu); // public double getSigma(); // public void setSigma(double sigma); // public void reSeed(long seed); // private double getNextDigest() throws MathIllegalStateException; // private double getNextReplay() throws IOException, MathIllegalStateException; // private double getNextUniform() throws MathIllegalArgumentException; // private double getNextExponential() throws MathIllegalArgumentException; // private double getNextGaussian() throws MathIllegalArgumentException; // } // // // Abstract Java Test Class // package org.apache.commons.math3.random; // // import java.net.URL; // import java.util.Arrays; // import org.apache.commons.math3.RetryRunner; // import org.apache.commons.math3.exception.MathIllegalStateException; // import org.apache.commons.math3.exception.ZeroException; // import org.apache.commons.math3.stat.descriptive.SummaryStatistics; // import org.junit.Assert; // import org.junit.Before; // import org.junit.Test; // import org.junit.runner.RunWith; // // // // @RunWith(RetryRunner.class) // public final class ValueServerTest { // private ValueServer vs = new ValueServer(new Well19937c(100)); // // @Before // public void setUp(); // @Test // public void testNextDigest() throws Exception; // @Test // public void testFixedSeed() throws Exception; // private void checkFixedSeed(ValueServer valueServer, int mode) throws Exception; // @Test // public void testNextDigestFail() throws Exception; // @Test // public void testEmptyReplayFile() throws Exception; // @Test // public void testEmptyDigestFile() throws Exception; // @Test // public void testReplay() throws Exception; // @Test // public void testModes() throws Exception; // @Test // public void testFill() throws Exception; // @Test // public void testProperties() throws Exception; // } // You are a professional Java test case writer, please create a test case named `testNextDigest` for the `ValueServer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * 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. */
src/test/java/org/apache/commons/math3/random/ValueServerTest.java
package org.apache.commons.math3.random; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.exception.MathIllegalStateException; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.exception.ZeroException; import org.apache.commons.math3.exception.util.LocalizedFormats;
public ValueServer(); @Deprecated public ValueServer(RandomDataImpl randomData); public ValueServer(RandomGenerator generator); public double getNext() throws IOException, MathIllegalStateException, MathIllegalArgumentException; public void fill(double[] values) throws IOException, MathIllegalStateException, MathIllegalArgumentException; public double[] fill(int length) throws IOException, MathIllegalStateException, MathIllegalArgumentException; public void computeDistribution() throws IOException, ZeroException, NullArgumentException; public void computeDistribution(int binCount) throws NullArgumentException, IOException, ZeroException; public int getMode(); public void setMode(int mode); public URL getValuesFileURL(); public void setValuesFileURL(String url) throws MalformedURLException; public void setValuesFileURL(URL url); public EmpiricalDistribution getEmpiricalDistribution(); public void resetReplayFile() throws IOException; public void closeReplayFile() throws IOException; public double getMu(); public void setMu(double mu); public double getSigma(); public void setSigma(double sigma); public void reSeed(long seed); private double getNextDigest() throws MathIllegalStateException; private double getNextReplay() throws IOException, MathIllegalStateException; private double getNextUniform() throws MathIllegalArgumentException; private double getNextExponential() throws MathIllegalArgumentException; private double getNextGaussian() throws MathIllegalArgumentException;
78
testNextDigest
```java // Abstract Java Tested Class package org.apache.commons.math3.random; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.exception.MathIllegalStateException; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.exception.ZeroException; import org.apache.commons.math3.exception.util.LocalizedFormats; public class ValueServer { public static final int DIGEST_MODE = 0; public static final int REPLAY_MODE = 1; public static final int UNIFORM_MODE = 2; public static final int EXPONENTIAL_MODE = 3; public static final int GAUSSIAN_MODE = 4; public static final int CONSTANT_MODE = 5; private int mode = 5; private URL valuesFileURL = null; private double mu = 0.0; private double sigma = 0.0; private EmpiricalDistribution empiricalDistribution = null; private BufferedReader filePointer = null; private final RandomDataImpl randomData; public ValueServer(); @Deprecated public ValueServer(RandomDataImpl randomData); public ValueServer(RandomGenerator generator); public double getNext() throws IOException, MathIllegalStateException, MathIllegalArgumentException; public void fill(double[] values) throws IOException, MathIllegalStateException, MathIllegalArgumentException; public double[] fill(int length) throws IOException, MathIllegalStateException, MathIllegalArgumentException; public void computeDistribution() throws IOException, ZeroException, NullArgumentException; public void computeDistribution(int binCount) throws NullArgumentException, IOException, ZeroException; public int getMode(); public void setMode(int mode); public URL getValuesFileURL(); public void setValuesFileURL(String url) throws MalformedURLException; public void setValuesFileURL(URL url); public EmpiricalDistribution getEmpiricalDistribution(); public void resetReplayFile() throws IOException; public void closeReplayFile() throws IOException; public double getMu(); public void setMu(double mu); public double getSigma(); public void setSigma(double sigma); public void reSeed(long seed); private double getNextDigest() throws MathIllegalStateException; private double getNextReplay() throws IOException, MathIllegalStateException; private double getNextUniform() throws MathIllegalArgumentException; private double getNextExponential() throws MathIllegalArgumentException; private double getNextGaussian() throws MathIllegalArgumentException; } // Abstract Java Test Class package org.apache.commons.math3.random; import java.net.URL; import java.util.Arrays; import org.apache.commons.math3.RetryRunner; import org.apache.commons.math3.exception.MathIllegalStateException; import org.apache.commons.math3.exception.ZeroException; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(RetryRunner.class) public final class ValueServerTest { private ValueServer vs = new ValueServer(new Well19937c(100)); @Before public void setUp(); @Test public void testNextDigest() throws Exception; @Test public void testFixedSeed() throws Exception; private void checkFixedSeed(ValueServer valueServer, int mode) throws Exception; @Test public void testNextDigestFail() throws Exception; @Test public void testEmptyReplayFile() throws Exception; @Test public void testEmptyDigestFile() throws Exception; @Test public void testReplay() throws Exception; @Test public void testModes() throws Exception; @Test public void testFill() throws Exception; @Test public void testProperties() throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testNextDigest` for the `ValueServer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * 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. */
53
// // Abstract Java Tested Class // package org.apache.commons.math3.random; // // import java.io.BufferedReader; // import java.io.IOException; // import java.io.InputStreamReader; // import java.net.MalformedURLException; // import java.net.URL; // import org.apache.commons.math3.exception.MathIllegalArgumentException; // import org.apache.commons.math3.exception.MathIllegalStateException; // import org.apache.commons.math3.exception.NullArgumentException; // import org.apache.commons.math3.exception.ZeroException; // import org.apache.commons.math3.exception.util.LocalizedFormats; // // // // public class ValueServer { // public static final int DIGEST_MODE = 0; // public static final int REPLAY_MODE = 1; // public static final int UNIFORM_MODE = 2; // public static final int EXPONENTIAL_MODE = 3; // public static final int GAUSSIAN_MODE = 4; // public static final int CONSTANT_MODE = 5; // private int mode = 5; // private URL valuesFileURL = null; // private double mu = 0.0; // private double sigma = 0.0; // private EmpiricalDistribution empiricalDistribution = null; // private BufferedReader filePointer = null; // private final RandomDataImpl randomData; // // public ValueServer(); // @Deprecated // public ValueServer(RandomDataImpl randomData); // public ValueServer(RandomGenerator generator); // public double getNext() throws IOException, MathIllegalStateException, MathIllegalArgumentException; // public void fill(double[] values) // throws IOException, MathIllegalStateException, MathIllegalArgumentException; // public double[] fill(int length) // throws IOException, MathIllegalStateException, MathIllegalArgumentException; // public void computeDistribution() throws IOException, ZeroException, NullArgumentException; // public void computeDistribution(int binCount) throws NullArgumentException, IOException, ZeroException; // public int getMode(); // public void setMode(int mode); // public URL getValuesFileURL(); // public void setValuesFileURL(String url) throws MalformedURLException; // public void setValuesFileURL(URL url); // public EmpiricalDistribution getEmpiricalDistribution(); // public void resetReplayFile() throws IOException; // public void closeReplayFile() throws IOException; // public double getMu(); // public void setMu(double mu); // public double getSigma(); // public void setSigma(double sigma); // public void reSeed(long seed); // private double getNextDigest() throws MathIllegalStateException; // private double getNextReplay() throws IOException, MathIllegalStateException; // private double getNextUniform() throws MathIllegalArgumentException; // private double getNextExponential() throws MathIllegalArgumentException; // private double getNextGaussian() throws MathIllegalArgumentException; // } // // // Abstract Java Test Class // package org.apache.commons.math3.random; // // import java.net.URL; // import java.util.Arrays; // import org.apache.commons.math3.RetryRunner; // import org.apache.commons.math3.exception.MathIllegalStateException; // import org.apache.commons.math3.exception.ZeroException; // import org.apache.commons.math3.stat.descriptive.SummaryStatistics; // import org.junit.Assert; // import org.junit.Before; // import org.junit.Test; // import org.junit.runner.RunWith; // // // // @RunWith(RetryRunner.class) // public final class ValueServerTest { // private ValueServer vs = new ValueServer(new Well19937c(100)); // // @Before // public void setUp(); // @Test // public void testNextDigest() throws Exception; // @Test // public void testFixedSeed() throws Exception; // private void checkFixedSeed(ValueServer valueServer, int mode) throws Exception; // @Test // public void testNextDigestFail() throws Exception; // @Test // public void testEmptyReplayFile() throws Exception; // @Test // public void testEmptyDigestFile() throws Exception; // @Test // public void testReplay() throws Exception; // @Test // public void testModes() throws Exception; // @Test // public void testFill() throws Exception; // @Test // public void testProperties() throws Exception; // } // You are a professional Java test case writer, please create a test case named `testNextDigest` for the `ValueServer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * 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 testNextDigest() throws Exception {
/** * 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. */
1
org.apache.commons.math3.random.ValueServer
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.math3.random; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.exception.MathIllegalStateException; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.exception.ZeroException; import org.apache.commons.math3.exception.util.LocalizedFormats; public class ValueServer { public static final int DIGEST_MODE = 0; public static final int REPLAY_MODE = 1; public static final int UNIFORM_MODE = 2; public static final int EXPONENTIAL_MODE = 3; public static final int GAUSSIAN_MODE = 4; public static final int CONSTANT_MODE = 5; private int mode = 5; private URL valuesFileURL = null; private double mu = 0.0; private double sigma = 0.0; private EmpiricalDistribution empiricalDistribution = null; private BufferedReader filePointer = null; private final RandomDataImpl randomData; public ValueServer(); @Deprecated public ValueServer(RandomDataImpl randomData); public ValueServer(RandomGenerator generator); public double getNext() throws IOException, MathIllegalStateException, MathIllegalArgumentException; public void fill(double[] values) throws IOException, MathIllegalStateException, MathIllegalArgumentException; public double[] fill(int length) throws IOException, MathIllegalStateException, MathIllegalArgumentException; public void computeDistribution() throws IOException, ZeroException, NullArgumentException; public void computeDistribution(int binCount) throws NullArgumentException, IOException, ZeroException; public int getMode(); public void setMode(int mode); public URL getValuesFileURL(); public void setValuesFileURL(String url) throws MalformedURLException; public void setValuesFileURL(URL url); public EmpiricalDistribution getEmpiricalDistribution(); public void resetReplayFile() throws IOException; public void closeReplayFile() throws IOException; public double getMu(); public void setMu(double mu); public double getSigma(); public void setSigma(double sigma); public void reSeed(long seed); private double getNextDigest() throws MathIllegalStateException; private double getNextReplay() throws IOException, MathIllegalStateException; private double getNextUniform() throws MathIllegalArgumentException; private double getNextExponential() throws MathIllegalArgumentException; private double getNextGaussian() throws MathIllegalArgumentException; } // Abstract Java Test Class package org.apache.commons.math3.random; import java.net.URL; import java.util.Arrays; import org.apache.commons.math3.RetryRunner; import org.apache.commons.math3.exception.MathIllegalStateException; import org.apache.commons.math3.exception.ZeroException; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(RetryRunner.class) public final class ValueServerTest { private ValueServer vs = new ValueServer(new Well19937c(100)); @Before public void setUp(); @Test public void testNextDigest() throws Exception; @Test public void testFixedSeed() throws Exception; private void checkFixedSeed(ValueServer valueServer, int mode) throws Exception; @Test public void testNextDigestFail() throws Exception; @Test public void testEmptyReplayFile() throws Exception; @Test public void testEmptyDigestFile() throws Exception; @Test public void testReplay() throws Exception; @Test public void testModes() throws Exception; @Test public void testFill() throws Exception; @Test public void testProperties() throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testNextDigest` for the `ValueServer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * 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 testNextDigest() throws Exception { ```
public class ValueServer
package org.apache.commons.math3.random; import java.net.URL; import java.util.Arrays; import org.apache.commons.math3.RetryRunner; import org.apache.commons.math3.exception.MathIllegalStateException; import org.apache.commons.math3.exception.ZeroException; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith;
@Before public void setUp(); @Test public void testNextDigest() throws Exception; @Test public void testFixedSeed() throws Exception; private void checkFixedSeed(ValueServer valueServer, int mode) throws Exception; @Test public void testNextDigestFail() throws Exception; @Test public void testEmptyReplayFile() throws Exception; @Test public void testEmptyDigestFile() throws Exception; @Test public void testReplay() throws Exception; @Test public void testModes() throws Exception; @Test public void testFill() throws Exception; @Test public void testProperties() throws Exception;
53ca0d6862c947bd37c15034ca082c8606d7549473586a1e4cde60d7f9b9a44c
[ "org.apache.commons.math3.random.ValueServerTest::testNextDigest" ]
public static final int DIGEST_MODE = 0; public static final int REPLAY_MODE = 1; public static final int UNIFORM_MODE = 2; public static final int EXPONENTIAL_MODE = 3; public static final int GAUSSIAN_MODE = 4; public static final int CONSTANT_MODE = 5; private int mode = 5; private URL valuesFileURL = null; private double mu = 0.0; private double sigma = 0.0; private EmpiricalDistribution empiricalDistribution = null; private BufferedReader filePointer = null; private final RandomDataImpl randomData;
@Test public void testNextDigest() throws Exception
private ValueServer vs = new ValueServer(new Well19937c(100));
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.net.URL; import java.util.Arrays; import org.apache.commons.math3.RetryRunner; import org.apache.commons.math3.exception.MathIllegalStateException; import org.apache.commons.math3.exception.ZeroException; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** * Test cases for the ValueServer class. * * @version $Id$ */ @RunWith(RetryRunner.class) public final class ValueServerTest { private ValueServer vs = new ValueServer(new Well19937c(100)); @Before public void setUp() { vs.setMode(ValueServer.DIGEST_MODE); URL url = getClass().getResource("testData.txt"); vs.setValuesFileURL(url); } /** * 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 testNextDigest() throws Exception { double next = 0.0; double tolerance = 0.1; vs.computeDistribution(); Assert.assertTrue("empirical distribution property", vs.getEmpiricalDistribution() != null); SummaryStatistics stats = new SummaryStatistics(); for (int i = 1; i < 1000; i++) { next = vs.getNext(); stats.addValue(next); } Assert.assertEquals("mean", 5.069831575018909, stats.getMean(), tolerance); Assert.assertEquals("std dev", 1.0173699343977738, stats.getStandardDeviation(), tolerance); vs.computeDistribution(500); stats = new SummaryStatistics(); for (int i = 1; i < 1000; i++) { next = vs.getNext(); stats.addValue(next); } Assert.assertEquals("mean", 5.069831575018909, stats.getMean(), tolerance); Assert.assertEquals("std dev", 1.0173699343977738, stats.getStandardDeviation(), tolerance); } /** * Verify that when provided with fixed seeds, stochastic modes * generate fixed sequences. Verifies the fix for MATH-654. */ @Test public void testFixedSeed() throws Exception { ValueServer valueServer = new ValueServer(); URL url = getClass().getResource("testData.txt"); valueServer.setValuesFileURL(url); valueServer.computeDistribution(); checkFixedSeed(valueServer, ValueServer.DIGEST_MODE); checkFixedSeed(valueServer, ValueServer.EXPONENTIAL_MODE); checkFixedSeed(valueServer, ValueServer.GAUSSIAN_MODE); checkFixedSeed(valueServer, ValueServer.UNIFORM_MODE); } /** * Do the check for {@link #testFixedSeed()} * @param mode ValueServer mode */ private void checkFixedSeed(ValueServer valueServer, int mode) throws Exception { valueServer.reSeed(1000); valueServer.setMode(mode); double[][] values = new double[2][100]; for (int i = 0; i < 100; i++) { values[0][i] = valueServer.getNext(); } valueServer.reSeed(1000); for (int i = 0; i < 100; i++) { values[1][i] = valueServer.getNext(); } Assert.assertTrue(Arrays.equals(values[0], values[1])); } /** * Make sure exception thrown if digest getNext is attempted * before loading empiricalDistribution. */ @Test public void testNextDigestFail() throws Exception { try { vs.getNext(); Assert.fail("Expecting IllegalStateException"); } catch (IllegalStateException ex) {} } @Test public void testEmptyReplayFile() throws Exception { try { URL url = getClass().getResource("emptyFile.txt"); vs.setMode(ValueServer.REPLAY_MODE); vs.setValuesFileURL(url); vs.getNext(); Assert.fail("an exception should have been thrown"); } catch (MathIllegalStateException mise) { // expected behavior } } @Test public void testEmptyDigestFile() throws Exception { try { URL url = getClass().getResource("emptyFile.txt"); vs.setMode(ValueServer.DIGEST_MODE); vs.setValuesFileURL(url); vs.computeDistribution(); Assert.fail("an exception should have been thrown"); } catch (ZeroException ze) { // expected behavior } } /** * Test ValueServer REPLAY_MODE using values in testData file.<br> * Check that the values 1,2,1001,1002 match data file values 1 and 2. * the sample data file. */ @Test public void testReplay() throws Exception { double firstDataValue = 4.038625496201205; double secondDataValue = 3.6485326248346936; double tolerance = 10E-15; double compareValue = 0.0d; vs.setMode(ValueServer.REPLAY_MODE); vs.resetReplayFile(); compareValue = vs.getNext(); Assert.assertEquals(compareValue,firstDataValue,tolerance); compareValue = vs.getNext(); Assert.assertEquals(compareValue,secondDataValue,tolerance); for (int i = 3; i < 1001; i++) { compareValue = vs.getNext(); } compareValue = vs.getNext(); Assert.assertEquals(compareValue,firstDataValue,tolerance); compareValue = vs.getNext(); Assert.assertEquals(compareValue,secondDataValue,tolerance); vs.closeReplayFile(); // make sure no NPE vs.closeReplayFile(); } /** * Test other ValueServer modes */ @Test public void testModes() throws Exception { vs.setMode(ValueServer.CONSTANT_MODE); vs.setMu(0); Assert.assertEquals("constant mode test",vs.getMu(),vs.getNext(),Double.MIN_VALUE); vs.setMode(ValueServer.UNIFORM_MODE); vs.setMu(2); double val = vs.getNext(); Assert.assertTrue(val > 0 && val < 4); vs.setSigma(1); vs.setMode(ValueServer.GAUSSIAN_MODE); val = vs.getNext(); Assert.assertTrue("gaussian value close enough to mean", val < vs.getMu() + 100*vs.getSigma()); vs.setMode(ValueServer.EXPONENTIAL_MODE); val = vs.getNext(); Assert.assertTrue(val > 0); try { vs.setMode(1000); vs.getNext(); Assert.fail("bad mode, expecting IllegalStateException"); } catch (IllegalStateException ex) { // ignored } } /** * Test fill */ @Test public void testFill() throws Exception { vs.setMode(ValueServer.CONSTANT_MODE); vs.setMu(2); double[] val = new double[5]; vs.fill(val); for (int i = 0; i < 5; i++) { Assert.assertEquals("fill test in place",2,val[i],Double.MIN_VALUE); } double v2[] = vs.fill(3); for (int i = 0; i < 3; i++) { Assert.assertEquals("fill test in place",2,v2[i],Double.MIN_VALUE); } } /** * Test getters to make Clover happy */ @Test public void testProperties() throws Exception { vs.setMode(ValueServer.CONSTANT_MODE); Assert.assertEquals("mode test",ValueServer.CONSTANT_MODE,vs.getMode()); vs.setValuesFileURL("http://www.apache.org"); URL url = vs.getValuesFileURL(); Assert.assertEquals("valuesFileURL test","http://www.apache.org",url.toString()); } }
[ { "be_test_class_file": "org/apache/commons/math3/random/ValueServer.java", "be_test_class_name": "org.apache.commons.math3.random.ValueServer", "be_test_function_name": "computeDistribution", "be_test_function_signature": "()V", "line_numbers": [ "199", "200" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/random/ValueServer.java", "be_test_class_name": "org.apache.commons.math3.random.ValueServer", "be_test_function_name": "computeDistribution", "be_test_function_signature": "(I)V", "line_numbers": [ "219", "220", "221", "222", "223" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/random/ValueServer.java", "be_test_class_name": "org.apache.commons.math3.random.ValueServer", "be_test_function_name": "getEmpiricalDistribution", "be_test_function_signature": "()Lorg/apache/commons/math3/random/EmpiricalDistribution;", "line_numbers": [ "283" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/random/ValueServer.java", "be_test_class_name": "org.apache.commons.math3.random.ValueServer", "be_test_function_name": "getNext", "be_test_function_signature": "()D", "line_numbers": [ "134", "135", "136", "137", "138", "139", "140", "141" ], "method_line_rate": 0.25 }, { "be_test_class_file": "org/apache/commons/math3/random/ValueServer.java", "be_test_class_name": "org.apache.commons.math3.random.ValueServer", "be_test_function_name": "getNextDigest", "be_test_function_signature": "()D", "line_numbers": [ "384", "386", "388" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "org/apache/commons/math3/random/ValueServer.java", "be_test_class_name": "org.apache.commons.math3.random.ValueServer", "be_test_function_name": "setMode", "be_test_function_signature": "(I)V", "line_numbers": [ "241", "242" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/random/ValueServer.java", "be_test_class_name": "org.apache.commons.math3.random.ValueServer", "be_test_function_name": "setValuesFileURL", "be_test_function_signature": "(Ljava/net/URL;)V", "line_numbers": [ "274", "275" ], "method_line_rate": 1 } ]
public class FunctionInjectorTest extends TestCase
public void testCanInlineReferenceToFunctionInExpression18() { // Call in within a call helperCanInlineReferenceToFunction(CanInlineResult.AFTER_PREPARATION, "function foo(){return _g();}; " + "function x() {1 + foo()() }", "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 `testCanInlineReferenceToFunctionInExpression18` for the `FunctionInjector` class, utilizing the provided abstract Java class context information and the following natural language annotations. // } // "foo", INLINE_BLOCK); // "x().test=foo();", // "/** @nosideeffects */ function foo(){return 'foo'};" + // "/** @nosideeffects */ function x(){return c};" + // "c = a;" + // "b.test = 'b';" + // "a.test = 'a';" + // "var a = {}, b = {}, c;" + // helperCanInlineReferenceToFunction(true, // // ... foo can be inlined because of x() is side-effect free. // public void testCanInlineReferenceToFunctionInExpression17() { // } // "foo", INLINE_BLOCK); // "x().test=foo();", // "/** @nosideeffects */ function foo(){return 'foo'};" + // "function x(){return c};" + // "c = a;" + // "b.test = 'b';" + // "a.test = 'a';" + // "var a = {}, b = {}, c;" + // helperCanInlineReferenceToFunction(false, // // ... foo can not be inlined because of possible side-effects of x() // public void testCanInlineReferenceToFunctionInExpression16() { // } // "foo", INLINE_BLOCK); // "c.test=foo();", // "/** @nosideeffects */ function foo(){return 'foo'};" +
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);
664
testCanInlineReferenceToFunctionInExpression18
```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 `testCanInlineReferenceToFunctionInExpression18` for the `FunctionInjector` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java // } // "foo", INLINE_BLOCK); // "x().test=foo();", // "/** @nosideeffects */ function foo(){return 'foo'};" + // "/** @nosideeffects */ function x(){return c};" + // "c = a;" + // "b.test = 'b';" + // "a.test = 'a';" + // "var a = {}, b = {}, c;" + // helperCanInlineReferenceToFunction(true, // // ... foo can be inlined because of x() is side-effect free. // public void testCanInlineReferenceToFunctionInExpression17() { // } // "foo", INLINE_BLOCK); // "x().test=foo();", // "/** @nosideeffects */ function foo(){return 'foo'};" + // "function x(){return c};" + // "c = a;" + // "b.test = 'b';" + // "a.test = 'a';" + // "var a = {}, b = {}, c;" + // helperCanInlineReferenceToFunction(false, // // ... foo can not be inlined because of possible side-effects of x() // public void testCanInlineReferenceToFunctionInExpression16() { // } // "foo", INLINE_BLOCK); // "c.test=foo();", // "/** @nosideeffects */ function foo(){return 'foo'};" +
658
// 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 `testCanInlineReferenceToFunctionInExpression18` for the `FunctionInjector` class, utilizing the provided abstract Java class context information and the following natural language annotations. // } // "foo", INLINE_BLOCK); // "x().test=foo();", // "/** @nosideeffects */ function foo(){return 'foo'};" + // "/** @nosideeffects */ function x(){return c};" + // "c = a;" + // "b.test = 'b';" + // "a.test = 'a';" + // "var a = {}, b = {}, c;" + // helperCanInlineReferenceToFunction(true, // // ... foo can be inlined because of x() is side-effect free. // public void testCanInlineReferenceToFunctionInExpression17() { // } // "foo", INLINE_BLOCK); // "x().test=foo();", // "/** @nosideeffects */ function foo(){return 'foo'};" + // "function x(){return c};" + // "c = a;" + // "b.test = 'b';" + // "a.test = 'a';" + // "var a = {}, b = {}, c;" + // helperCanInlineReferenceToFunction(false, // // ... foo can not be inlined because of possible side-effects of x() // public void testCanInlineReferenceToFunctionInExpression16() { // } // "foo", INLINE_BLOCK); // "c.test=foo();", // "/** @nosideeffects */ function foo(){return 'foo'};" + // "c = a;" + // "b.test = 'b';" + // "a.test = 'a';" + // "var a = {}, b = {}, c;" + // helperCanInlineReferenceToFunction(true, // // ... foo can be inlined as it is side-effect free. // public void testCanInlineReferenceToFunctionInExpression15() { // TODO(nicksantos): Re-enable with side-effect detection. public void testCanInlineReferenceToFunctionInExpression18() {
// } // "foo", INLINE_BLOCK); // "x().test=foo();", // "/** @nosideeffects */ function foo(){return 'foo'};" + // "/** @nosideeffects */ function x(){return c};" + // "c = a;" + // "b.test = 'b';" + // "a.test = 'a';" + // "var a = {}, b = {}, c;" + // helperCanInlineReferenceToFunction(true, // // ... foo can be inlined because of x() is side-effect free. // public void testCanInlineReferenceToFunctionInExpression17() { // } // "foo", INLINE_BLOCK); // "x().test=foo();", // "/** @nosideeffects */ function foo(){return 'foo'};" + // "function x(){return c};" + // "c = a;" + // "b.test = 'b';" + // "a.test = 'a';" + // "var a = {}, b = {}, c;" + // helperCanInlineReferenceToFunction(false, // // ... foo can not be inlined because of possible side-effects of x() // public void testCanInlineReferenceToFunctionInExpression16() { // } // "foo", INLINE_BLOCK); // "c.test=foo();", // "/** @nosideeffects */ function foo(){return 'foo'};" + // "c = a;" + // "b.test = 'b';" + // "a.test = 'a';" + // "var a = {}, b = {}, c;" + // helperCanInlineReferenceToFunction(true, // // ... foo can be inlined as it is side-effect free. // public void testCanInlineReferenceToFunctionInExpression15() { // 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 `testCanInlineReferenceToFunctionInExpression18` for the `FunctionInjector` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java // } // "foo", INLINE_BLOCK); // "x().test=foo();", // "/** @nosideeffects */ function foo(){return 'foo'};" + // "/** @nosideeffects */ function x(){return c};" + // "c = a;" + // "b.test = 'b';" + // "a.test = 'a';" + // "var a = {}, b = {}, c;" + // helperCanInlineReferenceToFunction(true, // // ... foo can be inlined because of x() is side-effect free. // public void testCanInlineReferenceToFunctionInExpression17() { // } // "foo", INLINE_BLOCK); // "x().test=foo();", // "/** @nosideeffects */ function foo(){return 'foo'};" + // "function x(){return c};" + // "c = a;" + // "b.test = 'b';" + // "a.test = 'a';" + // "var a = {}, b = {}, c;" + // helperCanInlineReferenceToFunction(false, // // ... foo can not be inlined because of possible side-effects of x() // public void testCanInlineReferenceToFunctionInExpression16() { // } // "foo", INLINE_BLOCK); // "c.test=foo();", // "/** @nosideeffects */ function foo(){return 'foo'};" + // "c = a;" + // "b.test = 'b';" + // "a.test = 'a';" + // "var a = {}, b = {}, c;" + // helperCanInlineReferenceToFunction(true, // // ... foo can be inlined as it is side-effect free. // public void testCanInlineReferenceToFunctionInExpression15() { // TODO(nicksantos): Re-enable with side-effect detection. public void testCanInlineReferenceToFunctionInExpression18() { ```
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);
5554179f0641b911fa0bc7cd25c1243f99bccb03cb84139216e49dc38e9d80e0
[ "com.google.javascript.jscomp.FunctionInjectorTest::testCanInlineReferenceToFunctionInExpression18" ]
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 testCanInlineReferenceToFunctionInExpression18()
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": "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.6111111111111112 }, { "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 } ]
public class AliasExternalsTest extends CompilerTestCase
public void testUnaliasable() { test("function foo() {" + "var x=arguments.length;" + "var y=arguments.length;" + "var z=arguments.length;" + "var w=arguments.length;" + "return x + y + z + w" + "};foo();", formatPropNameDecl("length") + "function foo() {" + "var x=arguments[$$PROP_length];" + "var y=arguments[$$PROP_length];" + "var z=arguments[$$PROP_length];" + "var w=arguments[$$PROP_length];" + "return x + y + z + w" + "};foo();"); test("var x=new ActiveXObject();" + "x.foo=\"bar\";" + "var y=new ActiveXObject();" + "y.foo=\"bar\";" + "var z=new ActiveXObject();" + "z.foo=\"bar\";", "var x=new ActiveXObject();" + "x.foo=\"bar\";" + "var y=new ActiveXObject();" + "y.foo=\"bar\";" + "var z=new ActiveXObject();" + "z.foo=\"bar\";"); test("var _a=eval('foo'),_b=eval('foo'),_c=eval('foo'),_d=eval('foo')," + "_e=eval('foo'),_f=eval('foo'),_g=eval('foo');", "var _a=eval('foo'),_b=eval('foo'),_c=eval('foo'),_d=eval('foo')," + "_e=eval('foo'),_f=eval('foo'),_g=eval('foo');"); }
// // Abstract Java Tested Class // package com.google.javascript.jscomp; // // import com.google.common.base.Preconditions; // import com.google.common.base.Strings; // import com.google.common.collect.Lists; // import com.google.common.collect.Maps; // import com.google.common.collect.Sets; // import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback; // 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.Arrays; // import java.util.IdentityHashMap; // import java.util.List; // import java.util.Map; // import java.util.Set; // import javax.annotation.Nullable; // // // // class AliasExternals implements CompilerPass { // private static final int DEFAULT_REQUIRED_USAGE = 4; // private int requiredUsage = DEFAULT_REQUIRED_USAGE; // private static final int MIN_PROP_SIZE = 4; // static final String PROTOTYPE_PROPERTY_NAME = // getArrayNotationNameFor("prototype"); // private final Map<String, Symbol> props = Maps.newHashMap(); // private final List<Node> accessors = Lists.newArrayList(); // private final List<Node> mutators = Lists.newArrayList(); // private final Map<Node, Node> replacementMap = // new IdentityHashMap<Node, Node>(); // private final Map<String, Symbol> globals = Maps.newHashMap(); // private final AbstractCompiler compiler; // private final JSModuleGraph moduleGraph; // private Node defaultRoot; // private Map<JSModule, Node> moduleRoots; // private final Set<String> unaliasableGlobals = Sets.newHashSet( // // While "arguments" is declared as a global extern, it really only has // // meaning inside function bodies and should not be aliased at a global // // level. // "arguments", // // Eval should not be aliased, per the ECMA-262 spec section 15.1.2.1 // "eval", // // "NodeFilter" is not defined in IE and throws an error if you try to // // do var foo = NodeFilter. // "NodeFilter", // // Calls to this special function are eliminated by the RenameProperties // // compiler pass. // "JSCompiler_renameProperty"); // private final Set<String> aliasableGlobals = Sets.newHashSet(); // // AliasExternals(AbstractCompiler compiler, JSModuleGraph moduleGraph); // AliasExternals(AbstractCompiler compiler, JSModuleGraph moduleGraph, // @Nullable String unaliasableGlobals, // @Nullable String aliasableGlobals); // public void setRequiredUsage(int usage); // @Override // public void process(Node externs, Node root); // private void aliasProperties(Node externs, Node root); // private void replaceAccessor(Node getPropNode); // private void replaceMutator(Node getPropNode); // private void replaceNode(Node parent, Node before, Node after); // private void addAccessorPropName(String propName, Node root); // private void addMutatorFunction(String propName, Node root); // private Node getAddingRoot(JSModule m); // private static String getMutatorFor(String prop); // private static String getArrayNotationNameFor(String prop); // private void aliasGlobals(Node externs, Node root); // private void replaceGlobalUse(Node globalUse); // private void addGlobalAliasNode(Symbol global, Node root); // private Symbol newSymbolForGlobalVar(Node name); // private Symbol newSymbolForProperty(String name); // public GetAliasableNames(final Set<String> whitelist); // @Override // public void visit(NodeTraversal t, Node n, Node parent); // @Override // public void visit(NodeTraversal t, Node n, Node parent); // private boolean canReplaceWithGetProp(Node propNameNode, Node getPropNode, // Node parent); // private boolean canReplaceWithSetProp(Node propNameNode, Node getPropNode, // Node parent); // private void getGlobalName(NodeTraversal t, Node dest, Node parent); // @Override // public void visit(NodeTraversal t, Node n, Node parent); // @Override // public void visit(NodeTraversal t, Node n, Node parent); // private Symbol(String name, boolean isConstant); // void recordAccessor(NodeTraversal t); // void recordMutator(NodeTraversal t); // } // // // Abstract Java Test Class // package com.google.javascript.jscomp; // // // // public class AliasExternalsTest extends CompilerTestCase { // private static String EXTERNS = // // Globals // "/** @const */ var window;" + // "/** @const */ var document;" + // "var arguments;var _USER_ID;var ActiveXObject;" + // "function eval(x) {}" + // // Properties // "window.setTimeout;" + // "window.eval;" + // "props.window;props.innerHTML;props.length;props.prototype;props.length;" + // // More globals // "/** @noalias */ var RangeObject; " + // "var /** @noalias */ RuntimeObject, SelectionObject;" + // "/** @noalias */ function NoAliasFunction() {};"; // private String unaliasableGlobals; // private String aliasableGlobals; // private static final String MODULE_SRC_ONE = // "a=b.length;a=b.length;a=b.length;"; // private static final String MODULE_SRC_TWO = "c=d.length;"; // // public AliasExternalsTest(); // @Override // protected int getNumRepetitions(); // @Override // public void setUp(); // public void testGlobalAlias(); // public void testUnaliasable(); // public void testAliasableGlobals(); // public void testAliasableAndUnaliasableGlobals(); // public void testGlobalAssigment(); // public void testNewOperator(); // public void testGetProp(); // public void testIgnoredOps(); // public void testSetProp(); // public void testParentChild(); // public void testModulesWithoutDependencies(); // public void testModulesWithDependencies(); // public void testPropAccessorPushedDeeper1(); // public void testPropAccessorPushedDeeper2(); // public void testPropAccessorPushedDeeper3(); // public void testPropAccessorNotPushedDeeper(); // public void testPropMutatorPushedDeeper(); // public void testPropMutatorNotPushedDeeper(); // public void testGlobalAliasPushedDeeper(); // public void testGlobalAliasNotPushedDeeper(); // public void testNoAliasAnnotationForSingleVar(); // public void testNoAliasAnnotationForMultiVarDeclaration(); // public void testNoAliasAnnotationForFunction(); // private String formatPropNameDecl(String prop); // private String formatSetPropFn(String prop); // @Override // protected CompilerPass getProcessor(Compiler compiler); // } // You are a professional Java test case writer, please create a test case named `testUnaliasable` for the `AliasExternals` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Some globals should not be aliased because they have special meaning * within the language (like arguments). */
test/com/google/javascript/jscomp/AliasExternalsTest.java
package com.google.javascript.jscomp; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback; 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.Arrays; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable;
AliasExternals(AbstractCompiler compiler, JSModuleGraph moduleGraph); AliasExternals(AbstractCompiler compiler, JSModuleGraph moduleGraph, @Nullable String unaliasableGlobals, @Nullable String aliasableGlobals); public void setRequiredUsage(int usage); @Override public void process(Node externs, Node root); private void aliasProperties(Node externs, Node root); private void replaceAccessor(Node getPropNode); private void replaceMutator(Node getPropNode); private void replaceNode(Node parent, Node before, Node after); private void addAccessorPropName(String propName, Node root); private void addMutatorFunction(String propName, Node root); private Node getAddingRoot(JSModule m); private static String getMutatorFor(String prop); private static String getArrayNotationNameFor(String prop); private void aliasGlobals(Node externs, Node root); private void replaceGlobalUse(Node globalUse); private void addGlobalAliasNode(Symbol global, Node root); private Symbol newSymbolForGlobalVar(Node name); private Symbol newSymbolForProperty(String name); public GetAliasableNames(final Set<String> whitelist); @Override public void visit(NodeTraversal t, Node n, Node parent); @Override public void visit(NodeTraversal t, Node n, Node parent); private boolean canReplaceWithGetProp(Node propNameNode, Node getPropNode, Node parent); private boolean canReplaceWithSetProp(Node propNameNode, Node getPropNode, Node parent); private void getGlobalName(NodeTraversal t, Node dest, Node parent); @Override public void visit(NodeTraversal t, Node n, Node parent); @Override public void visit(NodeTraversal t, Node n, Node parent); private Symbol(String name, boolean isConstant); void recordAccessor(NodeTraversal t); void recordMutator(NodeTraversal t);
123
testUnaliasable
```java // Abstract Java Tested Class package com.google.javascript.jscomp; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback; 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.Arrays; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; class AliasExternals implements CompilerPass { private static final int DEFAULT_REQUIRED_USAGE = 4; private int requiredUsage = DEFAULT_REQUIRED_USAGE; private static final int MIN_PROP_SIZE = 4; static final String PROTOTYPE_PROPERTY_NAME = getArrayNotationNameFor("prototype"); private final Map<String, Symbol> props = Maps.newHashMap(); private final List<Node> accessors = Lists.newArrayList(); private final List<Node> mutators = Lists.newArrayList(); private final Map<Node, Node> replacementMap = new IdentityHashMap<Node, Node>(); private final Map<String, Symbol> globals = Maps.newHashMap(); private final AbstractCompiler compiler; private final JSModuleGraph moduleGraph; private Node defaultRoot; private Map<JSModule, Node> moduleRoots; private final Set<String> unaliasableGlobals = Sets.newHashSet( // While "arguments" is declared as a global extern, it really only has // meaning inside function bodies and should not be aliased at a global // level. "arguments", // Eval should not be aliased, per the ECMA-262 spec section 15.1.2.1 "eval", // "NodeFilter" is not defined in IE and throws an error if you try to // do var foo = NodeFilter. "NodeFilter", // Calls to this special function are eliminated by the RenameProperties // compiler pass. "JSCompiler_renameProperty"); private final Set<String> aliasableGlobals = Sets.newHashSet(); AliasExternals(AbstractCompiler compiler, JSModuleGraph moduleGraph); AliasExternals(AbstractCompiler compiler, JSModuleGraph moduleGraph, @Nullable String unaliasableGlobals, @Nullable String aliasableGlobals); public void setRequiredUsage(int usage); @Override public void process(Node externs, Node root); private void aliasProperties(Node externs, Node root); private void replaceAccessor(Node getPropNode); private void replaceMutator(Node getPropNode); private void replaceNode(Node parent, Node before, Node after); private void addAccessorPropName(String propName, Node root); private void addMutatorFunction(String propName, Node root); private Node getAddingRoot(JSModule m); private static String getMutatorFor(String prop); private static String getArrayNotationNameFor(String prop); private void aliasGlobals(Node externs, Node root); private void replaceGlobalUse(Node globalUse); private void addGlobalAliasNode(Symbol global, Node root); private Symbol newSymbolForGlobalVar(Node name); private Symbol newSymbolForProperty(String name); public GetAliasableNames(final Set<String> whitelist); @Override public void visit(NodeTraversal t, Node n, Node parent); @Override public void visit(NodeTraversal t, Node n, Node parent); private boolean canReplaceWithGetProp(Node propNameNode, Node getPropNode, Node parent); private boolean canReplaceWithSetProp(Node propNameNode, Node getPropNode, Node parent); private void getGlobalName(NodeTraversal t, Node dest, Node parent); @Override public void visit(NodeTraversal t, Node n, Node parent); @Override public void visit(NodeTraversal t, Node n, Node parent); private Symbol(String name, boolean isConstant); void recordAccessor(NodeTraversal t); void recordMutator(NodeTraversal t); } // Abstract Java Test Class package com.google.javascript.jscomp; public class AliasExternalsTest extends CompilerTestCase { private static String EXTERNS = // Globals "/** @const */ var window;" + "/** @const */ var document;" + "var arguments;var _USER_ID;var ActiveXObject;" + "function eval(x) {}" + // Properties "window.setTimeout;" + "window.eval;" + "props.window;props.innerHTML;props.length;props.prototype;props.length;" + // More globals "/** @noalias */ var RangeObject; " + "var /** @noalias */ RuntimeObject, SelectionObject;" + "/** @noalias */ function NoAliasFunction() {};"; private String unaliasableGlobals; private String aliasableGlobals; private static final String MODULE_SRC_ONE = "a=b.length;a=b.length;a=b.length;"; private static final String MODULE_SRC_TWO = "c=d.length;"; public AliasExternalsTest(); @Override protected int getNumRepetitions(); @Override public void setUp(); public void testGlobalAlias(); public void testUnaliasable(); public void testAliasableGlobals(); public void testAliasableAndUnaliasableGlobals(); public void testGlobalAssigment(); public void testNewOperator(); public void testGetProp(); public void testIgnoredOps(); public void testSetProp(); public void testParentChild(); public void testModulesWithoutDependencies(); public void testModulesWithDependencies(); public void testPropAccessorPushedDeeper1(); public void testPropAccessorPushedDeeper2(); public void testPropAccessorPushedDeeper3(); public void testPropAccessorNotPushedDeeper(); public void testPropMutatorPushedDeeper(); public void testPropMutatorNotPushedDeeper(); public void testGlobalAliasPushedDeeper(); public void testGlobalAliasNotPushedDeeper(); public void testNoAliasAnnotationForSingleVar(); public void testNoAliasAnnotationForMultiVarDeclaration(); public void testNoAliasAnnotationForFunction(); private String formatPropNameDecl(String prop); private String formatSetPropFn(String prop); @Override protected CompilerPass getProcessor(Compiler compiler); } ``` You are a professional Java test case writer, please create a test case named `testUnaliasable` for the `AliasExternals` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Some globals should not be aliased because they have special meaning * within the language (like arguments). */
87
// // Abstract Java Tested Class // package com.google.javascript.jscomp; // // import com.google.common.base.Preconditions; // import com.google.common.base.Strings; // import com.google.common.collect.Lists; // import com.google.common.collect.Maps; // import com.google.common.collect.Sets; // import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback; // 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.Arrays; // import java.util.IdentityHashMap; // import java.util.List; // import java.util.Map; // import java.util.Set; // import javax.annotation.Nullable; // // // // class AliasExternals implements CompilerPass { // private static final int DEFAULT_REQUIRED_USAGE = 4; // private int requiredUsage = DEFAULT_REQUIRED_USAGE; // private static final int MIN_PROP_SIZE = 4; // static final String PROTOTYPE_PROPERTY_NAME = // getArrayNotationNameFor("prototype"); // private final Map<String, Symbol> props = Maps.newHashMap(); // private final List<Node> accessors = Lists.newArrayList(); // private final List<Node> mutators = Lists.newArrayList(); // private final Map<Node, Node> replacementMap = // new IdentityHashMap<Node, Node>(); // private final Map<String, Symbol> globals = Maps.newHashMap(); // private final AbstractCompiler compiler; // private final JSModuleGraph moduleGraph; // private Node defaultRoot; // private Map<JSModule, Node> moduleRoots; // private final Set<String> unaliasableGlobals = Sets.newHashSet( // // While "arguments" is declared as a global extern, it really only has // // meaning inside function bodies and should not be aliased at a global // // level. // "arguments", // // Eval should not be aliased, per the ECMA-262 spec section 15.1.2.1 // "eval", // // "NodeFilter" is not defined in IE and throws an error if you try to // // do var foo = NodeFilter. // "NodeFilter", // // Calls to this special function are eliminated by the RenameProperties // // compiler pass. // "JSCompiler_renameProperty"); // private final Set<String> aliasableGlobals = Sets.newHashSet(); // // AliasExternals(AbstractCompiler compiler, JSModuleGraph moduleGraph); // AliasExternals(AbstractCompiler compiler, JSModuleGraph moduleGraph, // @Nullable String unaliasableGlobals, // @Nullable String aliasableGlobals); // public void setRequiredUsage(int usage); // @Override // public void process(Node externs, Node root); // private void aliasProperties(Node externs, Node root); // private void replaceAccessor(Node getPropNode); // private void replaceMutator(Node getPropNode); // private void replaceNode(Node parent, Node before, Node after); // private void addAccessorPropName(String propName, Node root); // private void addMutatorFunction(String propName, Node root); // private Node getAddingRoot(JSModule m); // private static String getMutatorFor(String prop); // private static String getArrayNotationNameFor(String prop); // private void aliasGlobals(Node externs, Node root); // private void replaceGlobalUse(Node globalUse); // private void addGlobalAliasNode(Symbol global, Node root); // private Symbol newSymbolForGlobalVar(Node name); // private Symbol newSymbolForProperty(String name); // public GetAliasableNames(final Set<String> whitelist); // @Override // public void visit(NodeTraversal t, Node n, Node parent); // @Override // public void visit(NodeTraversal t, Node n, Node parent); // private boolean canReplaceWithGetProp(Node propNameNode, Node getPropNode, // Node parent); // private boolean canReplaceWithSetProp(Node propNameNode, Node getPropNode, // Node parent); // private void getGlobalName(NodeTraversal t, Node dest, Node parent); // @Override // public void visit(NodeTraversal t, Node n, Node parent); // @Override // public void visit(NodeTraversal t, Node n, Node parent); // private Symbol(String name, boolean isConstant); // void recordAccessor(NodeTraversal t); // void recordMutator(NodeTraversal t); // } // // // Abstract Java Test Class // package com.google.javascript.jscomp; // // // // public class AliasExternalsTest extends CompilerTestCase { // private static String EXTERNS = // // Globals // "/** @const */ var window;" + // "/** @const */ var document;" + // "var arguments;var _USER_ID;var ActiveXObject;" + // "function eval(x) {}" + // // Properties // "window.setTimeout;" + // "window.eval;" + // "props.window;props.innerHTML;props.length;props.prototype;props.length;" + // // More globals // "/** @noalias */ var RangeObject; " + // "var /** @noalias */ RuntimeObject, SelectionObject;" + // "/** @noalias */ function NoAliasFunction() {};"; // private String unaliasableGlobals; // private String aliasableGlobals; // private static final String MODULE_SRC_ONE = // "a=b.length;a=b.length;a=b.length;"; // private static final String MODULE_SRC_TWO = "c=d.length;"; // // public AliasExternalsTest(); // @Override // protected int getNumRepetitions(); // @Override // public void setUp(); // public void testGlobalAlias(); // public void testUnaliasable(); // public void testAliasableGlobals(); // public void testAliasableAndUnaliasableGlobals(); // public void testGlobalAssigment(); // public void testNewOperator(); // public void testGetProp(); // public void testIgnoredOps(); // public void testSetProp(); // public void testParentChild(); // public void testModulesWithoutDependencies(); // public void testModulesWithDependencies(); // public void testPropAccessorPushedDeeper1(); // public void testPropAccessorPushedDeeper2(); // public void testPropAccessorPushedDeeper3(); // public void testPropAccessorNotPushedDeeper(); // public void testPropMutatorPushedDeeper(); // public void testPropMutatorNotPushedDeeper(); // public void testGlobalAliasPushedDeeper(); // public void testGlobalAliasNotPushedDeeper(); // public void testNoAliasAnnotationForSingleVar(); // public void testNoAliasAnnotationForMultiVarDeclaration(); // public void testNoAliasAnnotationForFunction(); // private String formatPropNameDecl(String prop); // private String formatSetPropFn(String prop); // @Override // protected CompilerPass getProcessor(Compiler compiler); // } // You are a professional Java test case writer, please create a test case named `testUnaliasable` for the `AliasExternals` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Some globals should not be aliased because they have special meaning * within the language (like arguments). */ public void testUnaliasable() {
/** * Some globals should not be aliased because they have special meaning * within the language (like arguments). */
107
com.google.javascript.jscomp.AliasExternals
test
```java // Abstract Java Tested Class package com.google.javascript.jscomp; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback; 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.Arrays; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; class AliasExternals implements CompilerPass { private static final int DEFAULT_REQUIRED_USAGE = 4; private int requiredUsage = DEFAULT_REQUIRED_USAGE; private static final int MIN_PROP_SIZE = 4; static final String PROTOTYPE_PROPERTY_NAME = getArrayNotationNameFor("prototype"); private final Map<String, Symbol> props = Maps.newHashMap(); private final List<Node> accessors = Lists.newArrayList(); private final List<Node> mutators = Lists.newArrayList(); private final Map<Node, Node> replacementMap = new IdentityHashMap<Node, Node>(); private final Map<String, Symbol> globals = Maps.newHashMap(); private final AbstractCompiler compiler; private final JSModuleGraph moduleGraph; private Node defaultRoot; private Map<JSModule, Node> moduleRoots; private final Set<String> unaliasableGlobals = Sets.newHashSet( // While "arguments" is declared as a global extern, it really only has // meaning inside function bodies and should not be aliased at a global // level. "arguments", // Eval should not be aliased, per the ECMA-262 spec section 15.1.2.1 "eval", // "NodeFilter" is not defined in IE and throws an error if you try to // do var foo = NodeFilter. "NodeFilter", // Calls to this special function are eliminated by the RenameProperties // compiler pass. "JSCompiler_renameProperty"); private final Set<String> aliasableGlobals = Sets.newHashSet(); AliasExternals(AbstractCompiler compiler, JSModuleGraph moduleGraph); AliasExternals(AbstractCompiler compiler, JSModuleGraph moduleGraph, @Nullable String unaliasableGlobals, @Nullable String aliasableGlobals); public void setRequiredUsage(int usage); @Override public void process(Node externs, Node root); private void aliasProperties(Node externs, Node root); private void replaceAccessor(Node getPropNode); private void replaceMutator(Node getPropNode); private void replaceNode(Node parent, Node before, Node after); private void addAccessorPropName(String propName, Node root); private void addMutatorFunction(String propName, Node root); private Node getAddingRoot(JSModule m); private static String getMutatorFor(String prop); private static String getArrayNotationNameFor(String prop); private void aliasGlobals(Node externs, Node root); private void replaceGlobalUse(Node globalUse); private void addGlobalAliasNode(Symbol global, Node root); private Symbol newSymbolForGlobalVar(Node name); private Symbol newSymbolForProperty(String name); public GetAliasableNames(final Set<String> whitelist); @Override public void visit(NodeTraversal t, Node n, Node parent); @Override public void visit(NodeTraversal t, Node n, Node parent); private boolean canReplaceWithGetProp(Node propNameNode, Node getPropNode, Node parent); private boolean canReplaceWithSetProp(Node propNameNode, Node getPropNode, Node parent); private void getGlobalName(NodeTraversal t, Node dest, Node parent); @Override public void visit(NodeTraversal t, Node n, Node parent); @Override public void visit(NodeTraversal t, Node n, Node parent); private Symbol(String name, boolean isConstant); void recordAccessor(NodeTraversal t); void recordMutator(NodeTraversal t); } // Abstract Java Test Class package com.google.javascript.jscomp; public class AliasExternalsTest extends CompilerTestCase { private static String EXTERNS = // Globals "/** @const */ var window;" + "/** @const */ var document;" + "var arguments;var _USER_ID;var ActiveXObject;" + "function eval(x) {}" + // Properties "window.setTimeout;" + "window.eval;" + "props.window;props.innerHTML;props.length;props.prototype;props.length;" + // More globals "/** @noalias */ var RangeObject; " + "var /** @noalias */ RuntimeObject, SelectionObject;" + "/** @noalias */ function NoAliasFunction() {};"; private String unaliasableGlobals; private String aliasableGlobals; private static final String MODULE_SRC_ONE = "a=b.length;a=b.length;a=b.length;"; private static final String MODULE_SRC_TWO = "c=d.length;"; public AliasExternalsTest(); @Override protected int getNumRepetitions(); @Override public void setUp(); public void testGlobalAlias(); public void testUnaliasable(); public void testAliasableGlobals(); public void testAliasableAndUnaliasableGlobals(); public void testGlobalAssigment(); public void testNewOperator(); public void testGetProp(); public void testIgnoredOps(); public void testSetProp(); public void testParentChild(); public void testModulesWithoutDependencies(); public void testModulesWithDependencies(); public void testPropAccessorPushedDeeper1(); public void testPropAccessorPushedDeeper2(); public void testPropAccessorPushedDeeper3(); public void testPropAccessorNotPushedDeeper(); public void testPropMutatorPushedDeeper(); public void testPropMutatorNotPushedDeeper(); public void testGlobalAliasPushedDeeper(); public void testGlobalAliasNotPushedDeeper(); public void testNoAliasAnnotationForSingleVar(); public void testNoAliasAnnotationForMultiVarDeclaration(); public void testNoAliasAnnotationForFunction(); private String formatPropNameDecl(String prop); private String formatSetPropFn(String prop); @Override protected CompilerPass getProcessor(Compiler compiler); } ``` You are a professional Java test case writer, please create a test case named `testUnaliasable` for the `AliasExternals` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Some globals should not be aliased because they have special meaning * within the language (like arguments). */ public void testUnaliasable() { ```
class AliasExternals implements CompilerPass
package com.google.javascript.jscomp;
public AliasExternalsTest(); @Override protected int getNumRepetitions(); @Override public void setUp(); public void testGlobalAlias(); public void testUnaliasable(); public void testAliasableGlobals(); public void testAliasableAndUnaliasableGlobals(); public void testGlobalAssigment(); public void testNewOperator(); public void testGetProp(); public void testIgnoredOps(); public void testSetProp(); public void testParentChild(); public void testModulesWithoutDependencies(); public void testModulesWithDependencies(); public void testPropAccessorPushedDeeper1(); public void testPropAccessorPushedDeeper2(); public void testPropAccessorPushedDeeper3(); public void testPropAccessorNotPushedDeeper(); public void testPropMutatorPushedDeeper(); public void testPropMutatorNotPushedDeeper(); public void testGlobalAliasPushedDeeper(); public void testGlobalAliasNotPushedDeeper(); public void testNoAliasAnnotationForSingleVar(); public void testNoAliasAnnotationForMultiVarDeclaration(); public void testNoAliasAnnotationForFunction(); private String formatPropNameDecl(String prop); private String formatSetPropFn(String prop); @Override protected CompilerPass getProcessor(Compiler compiler);
5861a7cfe5e7aae08d23d087853820b1a5cc3acaf41914e438b6ea7dcdf8a3cc
[ "com.google.javascript.jscomp.AliasExternalsTest::testUnaliasable" ]
private static final int DEFAULT_REQUIRED_USAGE = 4; private int requiredUsage = DEFAULT_REQUIRED_USAGE; private static final int MIN_PROP_SIZE = 4; static final String PROTOTYPE_PROPERTY_NAME = getArrayNotationNameFor("prototype"); private final Map<String, Symbol> props = Maps.newHashMap(); private final List<Node> accessors = Lists.newArrayList(); private final List<Node> mutators = Lists.newArrayList(); private final Map<Node, Node> replacementMap = new IdentityHashMap<Node, Node>(); private final Map<String, Symbol> globals = Maps.newHashMap(); private final AbstractCompiler compiler; private final JSModuleGraph moduleGraph; private Node defaultRoot; private Map<JSModule, Node> moduleRoots; private final Set<String> unaliasableGlobals = Sets.newHashSet( // While "arguments" is declared as a global extern, it really only has // meaning inside function bodies and should not be aliased at a global // level. "arguments", // Eval should not be aliased, per the ECMA-262 spec section 15.1.2.1 "eval", // "NodeFilter" is not defined in IE and throws an error if you try to // do var foo = NodeFilter. "NodeFilter", // Calls to this special function are eliminated by the RenameProperties // compiler pass. "JSCompiler_renameProperty"); private final Set<String> aliasableGlobals = Sets.newHashSet();
public void testUnaliasable()
private static String EXTERNS = // Globals "/** @const */ var window;" + "/** @const */ var document;" + "var arguments;var _USER_ID;var ActiveXObject;" + "function eval(x) {}" + // Properties "window.setTimeout;" + "window.eval;" + "props.window;props.innerHTML;props.length;props.prototype;props.length;" + // More globals "/** @noalias */ var RangeObject; " + "var /** @noalias */ RuntimeObject, SelectionObject;" + "/** @noalias */ function NoAliasFunction() {};"; private String unaliasableGlobals; private String aliasableGlobals; private static final String MODULE_SRC_ONE = "a=b.length;a=b.length;a=b.length;"; private static final String MODULE_SRC_TWO = "c=d.length;";
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; /** * Tests for {@link AliasExternals}. * */ public class AliasExternalsTest extends CompilerTestCase { private static String EXTERNS = // Globals "/** @const */ var window;" + "/** @const */ var document;" + "var arguments;var _USER_ID;var ActiveXObject;" + "function eval(x) {}" + // Properties "window.setTimeout;" + "window.eval;" + "props.window;props.innerHTML;props.length;props.prototype;props.length;" + // More globals "/** @noalias */ var RangeObject; " + "var /** @noalias */ RuntimeObject, SelectionObject;" + "/** @noalias */ function NoAliasFunction() {};"; // Blacklist and whitelist of globals. Assign to these before running test // if you want to factor them in to the test, otherwise they will be null. private String unaliasableGlobals; private String aliasableGlobals; public AliasExternalsTest() { super(EXTERNS); } @Override protected int getNumRepetitions() { // This pass only runs once. return 1; } @Override public void setUp() { super.enableLineNumberCheck(false); super.enableNormalize(); unaliasableGlobals = null; aliasableGlobals = null; } /** * Test standard global aliasing. */ public void testGlobalAlias() { test("window.setTimeout(function() {}, 0);" + "var doc=window.document;" + "window.alert(\"foo\");" + "window.eval(\"1\");" + "window.location.href=\"http://www.example.com\";" + "function foo() {var window = \"bar\"; return window}foo();", "var GLOBAL_window=window;" + formatPropNameDecl("setTimeout") + "GLOBAL_window[$$PROP_setTimeout](function() {}, 0);" + "var doc=GLOBAL_window.document;" + "GLOBAL_window.alert(\"foo\");" + "GLOBAL_window.eval(\"1\");" + "GLOBAL_window.location.href=\"http://www.example.com\";" + "function foo() {var window = \"bar\"; return window}foo();"); } /** * Some globals should not be aliased because they have special meaning * within the language (like arguments). */ public void testUnaliasable() { test("function foo() {" + "var x=arguments.length;" + "var y=arguments.length;" + "var z=arguments.length;" + "var w=arguments.length;" + "return x + y + z + w" + "};foo();", formatPropNameDecl("length") + "function foo() {" + "var x=arguments[$$PROP_length];" + "var y=arguments[$$PROP_length];" + "var z=arguments[$$PROP_length];" + "var w=arguments[$$PROP_length];" + "return x + y + z + w" + "};foo();"); test("var x=new ActiveXObject();" + "x.foo=\"bar\";" + "var y=new ActiveXObject();" + "y.foo=\"bar\";" + "var z=new ActiveXObject();" + "z.foo=\"bar\";", "var x=new ActiveXObject();" + "x.foo=\"bar\";" + "var y=new ActiveXObject();" + "y.foo=\"bar\";" + "var z=new ActiveXObject();" + "z.foo=\"bar\";"); test("var _a=eval('foo'),_b=eval('foo'),_c=eval('foo'),_d=eval('foo')," + "_e=eval('foo'),_f=eval('foo'),_g=eval('foo');", "var _a=eval('foo'),_b=eval('foo'),_c=eval('foo'),_d=eval('foo')," + "_e=eval('foo'),_f=eval('foo'),_g=eval('foo');"); } /** * Test using a whitelist to explicitly alias only specific * identifiers. */ public void testAliasableGlobals() { aliasableGlobals = "notused,length"; test("function foo() {" + "var x=arguments.length;" + "var y=arguments.length;" + "var z=arguments.length;" + "var w=arguments.length;" + "return x + y + z + w" + "};foo();", formatPropNameDecl("length") + "function foo() {" + "var x=arguments[$$PROP_length];" + "var y=arguments[$$PROP_length];" + "var z=arguments[$$PROP_length];" + "var w=arguments[$$PROP_length];" + "return x + y + z + w" + "};foo();"); aliasableGlobals = "notused,notlength"; test("function foo() {" + "var x=arguments.length;" + "var y=arguments.length;" + "var z=arguments.length;" + "var w=arguments.length;" + "return x + y + z + w" + "};foo();", "function foo() {" + "var x=arguments.length;" + "var y=arguments.length;" + "var z=arguments.length;" + "var w=arguments.length;" + "return x + y + z + w" + "};foo();"); } /** * Test combined usage of aliasable and unaliasable global lists. */ public void testAliasableAndUnaliasableGlobals() { // Only aliasable provided - OK aliasableGlobals = "foo,bar"; unaliasableGlobals = ""; test("var x;", "var x;"); // Only unaliasable provided - OK aliasableGlobals = ""; unaliasableGlobals = "baz,qux"; test("var x;", "var x;"); // Both provided - bad aliasableGlobals = "foo,bar"; unaliasableGlobals = "baz,qux"; try { test("var x;", "var x;"); fail("Expected an IllegalArgumentException"); } catch (IllegalArgumentException ex) { // pass } } /** * Global variables that get re-assigned should not be aliased. */ public void testGlobalAssigment() { test("var x=_USER_ID+window;" + "var y=_USER_ID+window;" + "var z=_USER_ID+window;" + "var w=x+y+z;" + "_USER_ID = \"foo\";" + "window++;", "var x=_USER_ID+window;" + "var y=_USER_ID+window;" + "var z=_USER_ID+window;" + "var w=x+y+z;" + "_USER_ID = \"foo\";" + "window++"); } public void testNewOperator() { test("var x;new x(window);window;window;window;window;window", "var GLOBAL_window=window; var x;" + " new x(GLOBAL_window);GLOBAL_window;GLOBAL_window;" + " GLOBAL_window;GLOBAL_window;GLOBAL_window"); } /** * Test the standard replacement for GETPROP */ public void testGetProp() { test("function foo(a,b){return a.length > b.length;}", formatPropNameDecl("length") + "function foo(a, b){return a[$$PROP_length] > b[$$PROP_length];}"); test("Foo.prototype.bar = function() { return 'foo'; }", formatPropNameDecl("prototype") + "Foo[$$PROP_prototype].bar = function() { return 'foo'; }"); test("Foo.notreplaced = 5", "Foo.notreplaced=5"); } /** * Ops that should be ignored */ public void testIgnoredOps() { testSame("function foo() { this.length-- }"); testSame("function foo() { this.length++ }"); testSame("function foo() { this.length+=5 }"); testSame("function foo() { this.length-=5 }"); } /** * Test property setting */ public void testSetProp() { test("function foo() { this.innerHTML = 'hello!'; }", formatSetPropFn("innerHTML") + "function foo() { SETPROP_innerHTML(this, 'hello!'); }"); } /** * Test for modifying both parent and child, as all replacements * are on a single pass and modifying both involves being careful with * references. */ public void testParentChild() { test("a.length = b.length = c.length;", formatSetPropFn("length") + formatPropNameDecl("length") + "SETPROP_length(a, SETPROP_length(b, c[$$PROP_length]))"); } private static final String MODULE_SRC_ONE = "a=b.length;a=b.length;a=b.length;"; private static final String MODULE_SRC_TWO = "c=d.length;"; /** * Test that the code is placed in the first module when there are no * dependencies. */ public void testModulesWithoutDependencies() { test(createModules(MODULE_SRC_ONE, MODULE_SRC_TWO), new String[] { "var $$PROP_length=\"length\";a=b[$$PROP_length];" + "a=b[$$PROP_length];a=b[$$PROP_length];", "c=d[$$PROP_length];"}); } /** * Test that the code is placed in the first module when the second module * depends on the first. */ public void testModulesWithDependencies() { test(createModuleChain(MODULE_SRC_ONE, MODULE_SRC_TWO), new String[] { "var $$PROP_length=\"length\";a=b[$$PROP_length];" + "a=b[$$PROP_length];a=b[$$PROP_length];", "c=d[$$PROP_length];"}); } public void testPropAccessorPushedDeeper1() { test(createModuleChain("var a = \"foo\";", "var b = a.length;"), new String[] { "var a = \"foo\";", formatPropNameDecl("length") + "var b = a[$$PROP_length]" }); } public void testPropAccessorPushedDeeper2() { test(createModuleChain( "var a = \"foo\";", "var b = a.length;", "var c = a.length;"), new String[] { "var a = \"foo\";", formatPropNameDecl("length") + "var b = a[$$PROP_length]", "var c = a[$$PROP_length]" }); } public void testPropAccessorPushedDeeper3() { test(createModuleStar( "var a = \"foo\";", "var b = a.length;", "var c = a.length;"), new String[] { formatPropNameDecl("length") + "var a = \"foo\";", "var b = a[$$PROP_length]", "var c = a[$$PROP_length]" }); } public void testPropAccessorNotPushedDeeper() { test(createModuleChain("var a = \"foo\"; var b = a.length;", "var c = a.length;"), new String[] { formatPropNameDecl("length") + "var a = \"foo\"; var b = a[$$PROP_length]", "var c = a[$$PROP_length]" }); } public void testPropMutatorPushedDeeper() { test(createModuleChain("var a = [1];", "a.length = 0;"), new String[] { "var a = [1];", formatSetPropFn("length") + "SETPROP_length(a, 0);" }); } public void testPropMutatorNotPushedDeeper() { test(createModuleChain( "var a = [1]; a.length = 1;", "a.length = 0;"), new String[] { formatSetPropFn("length") + "var a = [1]; SETPROP_length(a, 1);", "SETPROP_length(a, 0);" }); } public void testGlobalAliasPushedDeeper() { test(createModuleChain( "var a = 1;", "var b = window, c = window, d = window, e = window;"), new String[] { "var a = 1;", "var GLOBAL_window = window;" + "var b = GLOBAL_window, c = GLOBAL_window, " + " d = GLOBAL_window, e = GLOBAL_window;" }); } public void testGlobalAliasNotPushedDeeper() { test(createModuleChain( "var a = 1, b = window;", "var c = window, d = window, e = window;"), new String[] { "var GLOBAL_window = window;" + "var a = 1, b = GLOBAL_window;", "var c = GLOBAL_window, " + " d = GLOBAL_window, e = GLOBAL_window;" }); } public void testNoAliasAnnotationForSingleVar() { testSame("[RangeObject, RangeObject, RangeObject]"); } public void testNoAliasAnnotationForMultiVarDeclaration() { test("[RuntimeObject, RuntimeObject, RuntimeObject," + " SelectionObject, SelectionObject, SelectionObject]", "var GLOBAL_SelectionObject = SelectionObject;" + "[RuntimeObject, RuntimeObject, RuntimeObject," + " GLOBAL_SelectionObject, GLOBAL_SelectionObject," + " GLOBAL_SelectionObject]"); } public void testNoAliasAnnotationForFunction() { testSame("[NoAliasFunction(), NoAliasFunction(), NoAliasFunction()]"); } private String formatPropNameDecl(String prop) { return "var $$PROP_" + prop + "='" + prop + "';"; } private String formatSetPropFn(String prop) { String mutatorName = "SETPROP_" + prop; String arg1 = mutatorName + "$a"; String arg2 = mutatorName + "$b"; return "function " + mutatorName + "(" + arg1 + "," + arg2 + ") {" + "return " + arg1 + "." + prop + "=" + arg2 + ";}"; } @Override protected CompilerPass getProcessor(Compiler compiler) { AliasExternals ae = new AliasExternals( compiler, compiler.getModuleGraph(), unaliasableGlobals, aliasableGlobals); ae.setRequiredUsage(1); return ae; } }
[ { "be_test_class_file": "com/google/javascript/jscomp/AliasExternals.java", "be_test_class_name": "com.google.javascript.jscomp.AliasExternals", "be_test_function_name": "access$1100", "be_test_function_signature": "(Lcom/google/javascript/jscomp/AliasExternals;)Lcom/google/javascript/jscomp/JSModuleGraph;", "line_numbers": [ "78" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/AliasExternals.java", "be_test_class_name": "com.google.javascript.jscomp.AliasExternals", "be_test_function_name": "addAccessorPropName", "be_test_function_signature": "(Ljava/lang/String;Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "381", "382", "384", "385", "386", "388", "389" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/AliasExternals.java", "be_test_class_name": "com.google.javascript.jscomp.AliasExternals", "be_test_function_name": "aliasGlobals", "be_test_function_signature": "(Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "567", "570", "573", "574", "575", "580", "581", "583", "584", "586", "589", "590", "591", "592", "593", "594", "597", "598" ], "method_line_rate": 0.8888888888888888 }, { "be_test_class_file": "com/google/javascript/jscomp/AliasExternals.java", "be_test_class_name": "com.google.javascript.jscomp.AliasExternals", "be_test_function_name": "aliasProperties", "be_test_function_signature": "(Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "223", "225", "228", "233", "234", "235", "236", "238", "239", "242", "244", "245", "246", "249", "250", "251", "256", "257", "258", "260", "262", "263", "264", "266", "267" ], "method_line_rate": 0.84 }, { "be_test_class_file": "com/google/javascript/jscomp/AliasExternals.java", "be_test_class_name": "com.google.javascript.jscomp.AliasExternals", "be_test_function_name": "getAddingRoot", "be_test_function_signature": "(Lcom/google/javascript/jscomp/JSModule;)Lcom/google/javascript/rhino/Node;", "line_numbers": [ "443", "444", "445", "446", "449", "450", "451", "452", "456" ], "method_line_rate": 0.2222222222222222 }, { "be_test_class_file": "com/google/javascript/jscomp/AliasExternals.java", "be_test_class_name": "com.google.javascript.jscomp.AliasExternals", "be_test_function_name": "getArrayNotationNameFor", "be_test_function_signature": "(Ljava/lang/String;)Ljava/lang/String;", "line_numbers": [ "562" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/AliasExternals.java", "be_test_class_name": "com.google.javascript.jscomp.AliasExternals", "be_test_function_name": "newSymbolForGlobalVar", "be_test_function_signature": "(Lcom/google/javascript/rhino/Node;)Lcom/google/javascript/jscomp/AliasExternals$Symbol;", "line_numbers": [ "734" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/AliasExternals.java", "be_test_class_name": "com.google.javascript.jscomp.AliasExternals", "be_test_function_name": "newSymbolForProperty", "be_test_function_signature": "(Ljava/lang/String;)Lcom/google/javascript/jscomp/AliasExternals$Symbol;", "line_numbers": [ "739" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/AliasExternals.java", "be_test_class_name": "com.google.javascript.jscomp.AliasExternals", "be_test_function_name": "process", "be_test_function_signature": "(Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "214", "215", "217", "218", "219" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/AliasExternals.java", "be_test_class_name": "com.google.javascript.jscomp.AliasExternals", "be_test_function_name": "replaceAccessor", "be_test_function_signature": "(Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "285", "286", "287", "288", "289", "291", "294", "295", "297", "299" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/AliasExternals.java", "be_test_class_name": "com.google.javascript.jscomp.AliasExternals", "be_test_function_name": "replaceGlobalUse", "be_test_function_signature": "(Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "691", "692", "693", "698", "700", "702" ], "method_line_rate": 0.5 }, { "be_test_class_file": "com/google/javascript/jscomp/AliasExternals.java", "be_test_class_name": "com.google.javascript.jscomp.AliasExternals", "be_test_function_name": "replaceNode", "be_test_function_signature": "(Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "357", "358", "360", "361", "362" ], "method_line_rate": 0.8 }, { "be_test_class_file": "com/google/javascript/jscomp/AliasExternals.java", "be_test_class_name": "com.google.javascript.jscomp.AliasExternals", "be_test_function_name": "setRequiredUsage", "be_test_function_signature": "(I)V", "line_numbers": [ "206", "207" ], "method_line_rate": 1 } ]
public class ObjectWriterTest extends BaseMapTest
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 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 `testPrettyPrinter` for the `ObjectWriter` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Test methods, normal operation /********************************************************** */
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;
79
testPrettyPrinter
```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 `testPrettyPrinter` for the `ObjectWriter` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Test methods, normal operation /********************************************************** */
60
// 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 `testPrettyPrinter` for the `ObjectWriter` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Test methods, normal operation /********************************************************** */ public void testPrettyPrinter() throws Exception {
/* /********************************************************** /* Test methods, normal operation /********************************************************** */
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 `testPrettyPrinter` for the `ObjectWriter` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Test methods, normal operation /********************************************************** */ public void testPrettyPrinter() 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);
5c16aedfbdd8ef70e1b03c495289dd1de66d0510132efbfef841cd17cd3a32e0
[ "com.fasterxml.jackson.databind.ObjectWriterTest::testPrettyPrinter" ]
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 testPrettyPrinter() 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": "_configAndWriteValue", "be_test_function_signature": "(Lcom/fasterxml/jackson/core/JsonGenerator;Ljava/lang/Object;)V", "line_numbers": [ "1114", "1115", "1116", "1117", "1120", "1121", "1122", "1123", "1124", "1125", "1126" ], "method_line_rate": 0.5454545454545454 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectWriter.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectWriter", "be_test_function_name": "_configureGenerator", "be_test_function_signature": "(Lcom/fasterxml/jackson/core/JsonGenerator;)V", "line_numbers": [ "1158", "1159", "1160" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectWriter.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectWriter", "be_test_function_name": "_new", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/ObjectWriter$GeneratorSettings;Lcom/fasterxml/jackson/databind/ObjectWriter$Prefetch;)Lcom/fasterxml/jackson/databind/ObjectWriter;", "line_numbers": [ "241", "242", "244" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectWriter.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectWriter", "be_test_function_name": "_serializerProvider", "be_test_function_signature": "()Lcom/fasterxml/jackson/databind/ser/DefaultSerializerProvider;", "line_numbers": [ "1086" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectWriter.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectWriter", "be_test_function_name": "with", "be_test_function_signature": "(Lcom/fasterxml/jackson/core/PrettyPrinter;)Lcom/fasterxml/jackson/databind/ObjectWriter;", "line_numbers": [ "497" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectWriter.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectWriter", "be_test_function_name": "withDefaultPrettyPrinter", "be_test_function_signature": "()Lcom/fasterxml/jackson/databind/ObjectWriter;", "line_numbers": [ "478" ], "method_line_rate": 1 }, { "be_test_class_file": "com/fasterxml/jackson/databind/ObjectWriter.java", "be_test_class_name": "com.fasterxml.jackson.databind.ObjectWriter", "be_test_function_name": "writeValueAsString", "be_test_function_signature": "(Ljava/lang/Object;)Ljava/lang/String;", "line_numbers": [ "991", "993", "994", "995", "996", "997", "998", "999" ], "method_line_rate": 0.5 } ]
public class ChartPanelTests extends TestCase implements ChartChangeListener, ChartMouseListener
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()); }
// 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_restoreAutoRangeBounds` for the `ChartPanel` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Checks that a call to the restoreAutoRangeBounds() method, for a plot * with more than one range 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();
334
test2502355_restoreAutoRangeBounds
```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_restoreAutoRangeBounds` 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 restoreAutoRangeBounds() method, for a plot * with more than one range axis, generates just one ChartChangeEvent. */
323
// 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_restoreAutoRangeBounds` for the `ChartPanel` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * 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() {
/** * Checks that a call to the restoreAutoRangeBounds() method, for a plot * with more than one range 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_restoreAutoRangeBounds` 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 restoreAutoRangeBounds() method, for a plot * with more than one range axis, generates just one ChartChangeEvent. */ public void test2502355_restoreAutoRangeBounds() { ```
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();
5fa18cb88877706694022ead07e10743b3abf0a1bd48693f87c68b672af6b21b
[ "org.jfree.chart.junit.ChartPanelTests::test2502355_restoreAutoRangeBounds" ]
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_restoreAutoRangeBounds()
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": "restoreAutoRangeBounds", "be_test_function_signature": "()V", "line_numbers": [ "2314", "2315", "2316", "2320", "2321", "2323", "2325", "2326", "2328" ], "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": "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": "updateUI", "be_test_function_signature": "()V", "line_numbers": [ "2942", "2943", "2945", "2946" ], "method_line_rate": 0.75 } ]
public class ZipArchiveEntryTest
@Test public void testCompressionMethod() throws Exception { final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new ByteArrayOutputStream()); final ZipArchiveEntry entry = new ZipArchiveEntry("foo"); assertEquals(-1, entry.getMethod()); assertFalse(zos.canWriteEntryData(entry)); entry.setMethod(ZipEntry.STORED); assertEquals(ZipEntry.STORED, entry.getMethod()); assertTrue(zos.canWriteEntryData(entry)); entry.setMethod(ZipEntry.DEFLATED); assertEquals(ZipEntry.DEFLATED, entry.getMethod()); assertTrue(zos.canWriteEntryData(entry)); // Test the unsupported "imploded" compression method (6) entry.setMethod(6); assertEquals(6, entry.getMethod()); assertFalse(zos.canWriteEntryData(entry)); zos.close(); }
// // Abstract Java Tested Class // package org.apache.commons.compress.archivers.zip; // // import org.apache.commons.compress.archivers.ArchiveEntry; // import org.apache.commons.compress.archivers.EntryStreamOffsets; // import java.io.File; // import java.util.ArrayList; // import java.util.Arrays; // import java.util.Date; // import java.util.List; // import java.util.zip.ZipException; // // // // public class ZipArchiveEntry extends java.util.zip.ZipEntry // implements ArchiveEntry, EntryStreamOffsets // { // public static final int PLATFORM_UNIX = 3; // public static final int PLATFORM_FAT = 0; // public static final int CRC_UNKNOWN = -1; // private static final int SHORT_MASK = 0xFFFF; // private static final int SHORT_SHIFT = 16; // private static final byte[] EMPTY = new byte[0]; // private int method = ZipMethod.UNKNOWN_CODE; // private long size = SIZE_UNKNOWN; // private int internalAttributes = 0; // private int versionRequired; // private int versionMadeBy; // private int platform = PLATFORM_FAT; // private int rawFlag; // private long externalAttributes = 0; // private int alignment = 0; // private ZipExtraField[] extraFields; // private UnparseableExtraFieldData unparseableExtra = null; // private String name = null; // private byte[] rawName = null; // private GeneralPurposeBit gpb = new GeneralPurposeBit(); // private static final ZipExtraField[] noExtraFields = new ZipExtraField[0]; // private long localHeaderOffset = OFFSET_UNKNOWN; // private long dataOffset = OFFSET_UNKNOWN; // private boolean isStreamContiguous = false; // private NameSource nameSource = NameSource.NAME; // private CommentSource commentSource = CommentSource.COMMENT; // // public ZipArchiveEntry(final String name); // public ZipArchiveEntry(final java.util.zip.ZipEntry entry) throws ZipException; // public ZipArchiveEntry(final ZipArchiveEntry entry) throws ZipException; // protected ZipArchiveEntry(); // public ZipArchiveEntry(final File inputFile, final String entryName); // @Override // public Object clone(); // @Override // public int getMethod(); // @Override // public void setMethod(final int method); // public int getInternalAttributes(); // public void setInternalAttributes(final int value); // public long getExternalAttributes(); // public void setExternalAttributes(final long value); // public void setUnixMode(final int mode); // public int getUnixMode(); // public boolean isUnixSymlink(); // public int getPlatform(); // protected void setPlatform(final int platform); // protected int getAlignment(); // public void setAlignment(int alignment); // public void setExtraFields(final ZipExtraField[] fields); // public ZipExtraField[] getExtraFields(); // public ZipExtraField[] getExtraFields(final boolean includeUnparseable); // private ZipExtraField[] getParseableExtraFieldsNoCopy(); // private ZipExtraField[] getParseableExtraFields(); // private ZipExtraField[] getAllExtraFieldsNoCopy(); // private ZipExtraField[] copyOf(final ZipExtraField[] src); // private ZipExtraField[] copyOf(final ZipExtraField[] src, final int length); // private ZipExtraField[] getMergedFields(); // private ZipExtraField[] getUnparseableOnly(); // private ZipExtraField[] getAllExtraFields(); // public void addExtraField(final ZipExtraField ze); // public void addAsFirstExtraField(final ZipExtraField ze); // public void removeExtraField(final ZipShort type); // public void removeUnparseableExtraFieldData(); // public ZipExtraField getExtraField(final ZipShort type); // public UnparseableExtraFieldData getUnparseableExtraFieldData(); // @Override // public void setExtra(final byte[] extra) throws RuntimeException; // protected void setExtra(); // public void setCentralDirectoryExtra(final byte[] b); // public byte[] getLocalFileDataExtra(); // public byte[] getCentralDirectoryExtra(); // @Override // public String getName(); // @Override // public boolean isDirectory(); // protected void setName(String name); // @Override // public long getSize(); // @Override // public void setSize(final long size); // protected void setName(final String name, final byte[] rawName); // public byte[] getRawName(); // protected long getLocalHeaderOffset(); // protected void setLocalHeaderOffset(long localHeaderOffset); // @Override // public long getDataOffset(); // protected void setDataOffset(long dataOffset); // @Override // public boolean isStreamContiguous(); // protected void setStreamContiguous(boolean isStreamContiguous); // @Override // public int hashCode(); // public GeneralPurposeBit getGeneralPurposeBit(); // public void setGeneralPurposeBit(final GeneralPurposeBit b); // private void mergeExtraFields(final ZipExtraField[] f, final boolean local) // throws ZipException; // @Override // public Date getLastModifiedDate(); // @Override // public boolean equals(final Object obj); // public void setVersionMadeBy(final int versionMadeBy); // public void setVersionRequired(final int versionRequired); // public int getVersionRequired(); // public int getVersionMadeBy(); // public int getRawFlag(); // public void setRawFlag(final int rawFlag); // public NameSource getNameSource(); // public void setNameSource(NameSource nameSource); // public CommentSource getCommentSource(); // public void setCommentSource(CommentSource commentSource); // } // // // Abstract Java Test Class // package org.apache.commons.compress.archivers.zip; // // import static org.apache.commons.compress.AbstractTestCase.getFile; // import static org.junit.Assert.*; // import java.io.ByteArrayOutputStream; // import java.util.zip.ZipEntry; // import org.junit.Test; // // // // public class ZipArchiveEntryTest { // // // @Test // public void testExtraFields(); // @Test // public void testExtraFieldMerging(); // @Test // public void testAddAsFirstExtraField(); // @Test // public void testUnixMode(); // @Test // public void testCompressionMethod() throws Exception; // @Test // public void testNotEquals(); // @Test // public void testNullCommentEqualsEmptyComment(); // @Test // public void testCopyConstructor() throws Exception; // @Test // public void isUnixSymlinkIsFalseIfMoreThanOneFlagIsSet() throws Exception; // @Test // public void testIsUnixSymlink(); // } // You are a professional Java test case writer, please create a test case named `testCompressionMethod` for the `ZipArchiveEntry` 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-93" * >COMPRESS-93</a>. */
src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveEntryTest.java
package org.apache.commons.compress.archivers.zip; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.EntryStreamOffsets; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.zip.ZipException;
public ZipArchiveEntry(final String name); public ZipArchiveEntry(final java.util.zip.ZipEntry entry) throws ZipException; public ZipArchiveEntry(final ZipArchiveEntry entry) throws ZipException; protected ZipArchiveEntry(); public ZipArchiveEntry(final File inputFile, final String entryName); @Override public Object clone(); @Override public int getMethod(); @Override public void setMethod(final int method); public int getInternalAttributes(); public void setInternalAttributes(final int value); public long getExternalAttributes(); public void setExternalAttributes(final long value); public void setUnixMode(final int mode); public int getUnixMode(); public boolean isUnixSymlink(); public int getPlatform(); protected void setPlatform(final int platform); protected int getAlignment(); public void setAlignment(int alignment); public void setExtraFields(final ZipExtraField[] fields); public ZipExtraField[] getExtraFields(); public ZipExtraField[] getExtraFields(final boolean includeUnparseable); private ZipExtraField[] getParseableExtraFieldsNoCopy(); private ZipExtraField[] getParseableExtraFields(); private ZipExtraField[] getAllExtraFieldsNoCopy(); private ZipExtraField[] copyOf(final ZipExtraField[] src); private ZipExtraField[] copyOf(final ZipExtraField[] src, final int length); private ZipExtraField[] getMergedFields(); private ZipExtraField[] getUnparseableOnly(); private ZipExtraField[] getAllExtraFields(); public void addExtraField(final ZipExtraField ze); public void addAsFirstExtraField(final ZipExtraField ze); public void removeExtraField(final ZipShort type); public void removeUnparseableExtraFieldData(); public ZipExtraField getExtraField(final ZipShort type); public UnparseableExtraFieldData getUnparseableExtraFieldData(); @Override public void setExtra(final byte[] extra) throws RuntimeException; protected void setExtra(); public void setCentralDirectoryExtra(final byte[] b); public byte[] getLocalFileDataExtra(); public byte[] getCentralDirectoryExtra(); @Override public String getName(); @Override public boolean isDirectory(); protected void setName(String name); @Override public long getSize(); @Override public void setSize(final long size); protected void setName(final String name, final byte[] rawName); public byte[] getRawName(); protected long getLocalHeaderOffset(); protected void setLocalHeaderOffset(long localHeaderOffset); @Override public long getDataOffset(); protected void setDataOffset(long dataOffset); @Override public boolean isStreamContiguous(); protected void setStreamContiguous(boolean isStreamContiguous); @Override public int hashCode(); public GeneralPurposeBit getGeneralPurposeBit(); public void setGeneralPurposeBit(final GeneralPurposeBit b); private void mergeExtraFields(final ZipExtraField[] f, final boolean local) throws ZipException; @Override public Date getLastModifiedDate(); @Override public boolean equals(final Object obj); public void setVersionMadeBy(final int versionMadeBy); public void setVersionRequired(final int versionRequired); public int getVersionRequired(); public int getVersionMadeBy(); public int getRawFlag(); public void setRawFlag(final int rawFlag); public NameSource getNameSource(); public void setNameSource(NameSource nameSource); public CommentSource getCommentSource(); public void setCommentSource(CommentSource commentSource);
231
testCompressionMethod
```java // Abstract Java Tested Class package org.apache.commons.compress.archivers.zip; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.EntryStreamOffsets; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.zip.ZipException; public class ZipArchiveEntry extends java.util.zip.ZipEntry implements ArchiveEntry, EntryStreamOffsets { public static final int PLATFORM_UNIX = 3; public static final int PLATFORM_FAT = 0; public static final int CRC_UNKNOWN = -1; private static final int SHORT_MASK = 0xFFFF; private static final int SHORT_SHIFT = 16; private static final byte[] EMPTY = new byte[0]; private int method = ZipMethod.UNKNOWN_CODE; private long size = SIZE_UNKNOWN; private int internalAttributes = 0; private int versionRequired; private int versionMadeBy; private int platform = PLATFORM_FAT; private int rawFlag; private long externalAttributes = 0; private int alignment = 0; private ZipExtraField[] extraFields; private UnparseableExtraFieldData unparseableExtra = null; private String name = null; private byte[] rawName = null; private GeneralPurposeBit gpb = new GeneralPurposeBit(); private static final ZipExtraField[] noExtraFields = new ZipExtraField[0]; private long localHeaderOffset = OFFSET_UNKNOWN; private long dataOffset = OFFSET_UNKNOWN; private boolean isStreamContiguous = false; private NameSource nameSource = NameSource.NAME; private CommentSource commentSource = CommentSource.COMMENT; public ZipArchiveEntry(final String name); public ZipArchiveEntry(final java.util.zip.ZipEntry entry) throws ZipException; public ZipArchiveEntry(final ZipArchiveEntry entry) throws ZipException; protected ZipArchiveEntry(); public ZipArchiveEntry(final File inputFile, final String entryName); @Override public Object clone(); @Override public int getMethod(); @Override public void setMethod(final int method); public int getInternalAttributes(); public void setInternalAttributes(final int value); public long getExternalAttributes(); public void setExternalAttributes(final long value); public void setUnixMode(final int mode); public int getUnixMode(); public boolean isUnixSymlink(); public int getPlatform(); protected void setPlatform(final int platform); protected int getAlignment(); public void setAlignment(int alignment); public void setExtraFields(final ZipExtraField[] fields); public ZipExtraField[] getExtraFields(); public ZipExtraField[] getExtraFields(final boolean includeUnparseable); private ZipExtraField[] getParseableExtraFieldsNoCopy(); private ZipExtraField[] getParseableExtraFields(); private ZipExtraField[] getAllExtraFieldsNoCopy(); private ZipExtraField[] copyOf(final ZipExtraField[] src); private ZipExtraField[] copyOf(final ZipExtraField[] src, final int length); private ZipExtraField[] getMergedFields(); private ZipExtraField[] getUnparseableOnly(); private ZipExtraField[] getAllExtraFields(); public void addExtraField(final ZipExtraField ze); public void addAsFirstExtraField(final ZipExtraField ze); public void removeExtraField(final ZipShort type); public void removeUnparseableExtraFieldData(); public ZipExtraField getExtraField(final ZipShort type); public UnparseableExtraFieldData getUnparseableExtraFieldData(); @Override public void setExtra(final byte[] extra) throws RuntimeException; protected void setExtra(); public void setCentralDirectoryExtra(final byte[] b); public byte[] getLocalFileDataExtra(); public byte[] getCentralDirectoryExtra(); @Override public String getName(); @Override public boolean isDirectory(); protected void setName(String name); @Override public long getSize(); @Override public void setSize(final long size); protected void setName(final String name, final byte[] rawName); public byte[] getRawName(); protected long getLocalHeaderOffset(); protected void setLocalHeaderOffset(long localHeaderOffset); @Override public long getDataOffset(); protected void setDataOffset(long dataOffset); @Override public boolean isStreamContiguous(); protected void setStreamContiguous(boolean isStreamContiguous); @Override public int hashCode(); public GeneralPurposeBit getGeneralPurposeBit(); public void setGeneralPurposeBit(final GeneralPurposeBit b); private void mergeExtraFields(final ZipExtraField[] f, final boolean local) throws ZipException; @Override public Date getLastModifiedDate(); @Override public boolean equals(final Object obj); public void setVersionMadeBy(final int versionMadeBy); public void setVersionRequired(final int versionRequired); public int getVersionRequired(); public int getVersionMadeBy(); public int getRawFlag(); public void setRawFlag(final int rawFlag); public NameSource getNameSource(); public void setNameSource(NameSource nameSource); public CommentSource getCommentSource(); public void setCommentSource(CommentSource commentSource); } // Abstract Java Test Class package org.apache.commons.compress.archivers.zip; import static org.apache.commons.compress.AbstractTestCase.getFile; import static org.junit.Assert.*; import java.io.ByteArrayOutputStream; import java.util.zip.ZipEntry; import org.junit.Test; public class ZipArchiveEntryTest { @Test public void testExtraFields(); @Test public void testExtraFieldMerging(); @Test public void testAddAsFirstExtraField(); @Test public void testUnixMode(); @Test public void testCompressionMethod() throws Exception; @Test public void testNotEquals(); @Test public void testNullCommentEqualsEmptyComment(); @Test public void testCopyConstructor() throws Exception; @Test public void isUnixSymlinkIsFalseIfMoreThanOneFlagIsSet() throws Exception; @Test public void testIsUnixSymlink(); } ``` You are a professional Java test case writer, please create a test case named `testCompressionMethod` for the `ZipArchiveEntry` 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-93" * >COMPRESS-93</a>. */
210
// // Abstract Java Tested Class // package org.apache.commons.compress.archivers.zip; // // import org.apache.commons.compress.archivers.ArchiveEntry; // import org.apache.commons.compress.archivers.EntryStreamOffsets; // import java.io.File; // import java.util.ArrayList; // import java.util.Arrays; // import java.util.Date; // import java.util.List; // import java.util.zip.ZipException; // // // // public class ZipArchiveEntry extends java.util.zip.ZipEntry // implements ArchiveEntry, EntryStreamOffsets // { // public static final int PLATFORM_UNIX = 3; // public static final int PLATFORM_FAT = 0; // public static final int CRC_UNKNOWN = -1; // private static final int SHORT_MASK = 0xFFFF; // private static final int SHORT_SHIFT = 16; // private static final byte[] EMPTY = new byte[0]; // private int method = ZipMethod.UNKNOWN_CODE; // private long size = SIZE_UNKNOWN; // private int internalAttributes = 0; // private int versionRequired; // private int versionMadeBy; // private int platform = PLATFORM_FAT; // private int rawFlag; // private long externalAttributes = 0; // private int alignment = 0; // private ZipExtraField[] extraFields; // private UnparseableExtraFieldData unparseableExtra = null; // private String name = null; // private byte[] rawName = null; // private GeneralPurposeBit gpb = new GeneralPurposeBit(); // private static final ZipExtraField[] noExtraFields = new ZipExtraField[0]; // private long localHeaderOffset = OFFSET_UNKNOWN; // private long dataOffset = OFFSET_UNKNOWN; // private boolean isStreamContiguous = false; // private NameSource nameSource = NameSource.NAME; // private CommentSource commentSource = CommentSource.COMMENT; // // public ZipArchiveEntry(final String name); // public ZipArchiveEntry(final java.util.zip.ZipEntry entry) throws ZipException; // public ZipArchiveEntry(final ZipArchiveEntry entry) throws ZipException; // protected ZipArchiveEntry(); // public ZipArchiveEntry(final File inputFile, final String entryName); // @Override // public Object clone(); // @Override // public int getMethod(); // @Override // public void setMethod(final int method); // public int getInternalAttributes(); // public void setInternalAttributes(final int value); // public long getExternalAttributes(); // public void setExternalAttributes(final long value); // public void setUnixMode(final int mode); // public int getUnixMode(); // public boolean isUnixSymlink(); // public int getPlatform(); // protected void setPlatform(final int platform); // protected int getAlignment(); // public void setAlignment(int alignment); // public void setExtraFields(final ZipExtraField[] fields); // public ZipExtraField[] getExtraFields(); // public ZipExtraField[] getExtraFields(final boolean includeUnparseable); // private ZipExtraField[] getParseableExtraFieldsNoCopy(); // private ZipExtraField[] getParseableExtraFields(); // private ZipExtraField[] getAllExtraFieldsNoCopy(); // private ZipExtraField[] copyOf(final ZipExtraField[] src); // private ZipExtraField[] copyOf(final ZipExtraField[] src, final int length); // private ZipExtraField[] getMergedFields(); // private ZipExtraField[] getUnparseableOnly(); // private ZipExtraField[] getAllExtraFields(); // public void addExtraField(final ZipExtraField ze); // public void addAsFirstExtraField(final ZipExtraField ze); // public void removeExtraField(final ZipShort type); // public void removeUnparseableExtraFieldData(); // public ZipExtraField getExtraField(final ZipShort type); // public UnparseableExtraFieldData getUnparseableExtraFieldData(); // @Override // public void setExtra(final byte[] extra) throws RuntimeException; // protected void setExtra(); // public void setCentralDirectoryExtra(final byte[] b); // public byte[] getLocalFileDataExtra(); // public byte[] getCentralDirectoryExtra(); // @Override // public String getName(); // @Override // public boolean isDirectory(); // protected void setName(String name); // @Override // public long getSize(); // @Override // public void setSize(final long size); // protected void setName(final String name, final byte[] rawName); // public byte[] getRawName(); // protected long getLocalHeaderOffset(); // protected void setLocalHeaderOffset(long localHeaderOffset); // @Override // public long getDataOffset(); // protected void setDataOffset(long dataOffset); // @Override // public boolean isStreamContiguous(); // protected void setStreamContiguous(boolean isStreamContiguous); // @Override // public int hashCode(); // public GeneralPurposeBit getGeneralPurposeBit(); // public void setGeneralPurposeBit(final GeneralPurposeBit b); // private void mergeExtraFields(final ZipExtraField[] f, final boolean local) // throws ZipException; // @Override // public Date getLastModifiedDate(); // @Override // public boolean equals(final Object obj); // public void setVersionMadeBy(final int versionMadeBy); // public void setVersionRequired(final int versionRequired); // public int getVersionRequired(); // public int getVersionMadeBy(); // public int getRawFlag(); // public void setRawFlag(final int rawFlag); // public NameSource getNameSource(); // public void setNameSource(NameSource nameSource); // public CommentSource getCommentSource(); // public void setCommentSource(CommentSource commentSource); // } // // // Abstract Java Test Class // package org.apache.commons.compress.archivers.zip; // // import static org.apache.commons.compress.AbstractTestCase.getFile; // import static org.junit.Assert.*; // import java.io.ByteArrayOutputStream; // import java.util.zip.ZipEntry; // import org.junit.Test; // // // // public class ZipArchiveEntryTest { // // // @Test // public void testExtraFields(); // @Test // public void testExtraFieldMerging(); // @Test // public void testAddAsFirstExtraField(); // @Test // public void testUnixMode(); // @Test // public void testCompressionMethod() throws Exception; // @Test // public void testNotEquals(); // @Test // public void testNullCommentEqualsEmptyComment(); // @Test // public void testCopyConstructor() throws Exception; // @Test // public void isUnixSymlinkIsFalseIfMoreThanOneFlagIsSet() throws Exception; // @Test // public void testIsUnixSymlink(); // } // You are a professional Java test case writer, please create a test case named `testCompressionMethod` for the `ZipArchiveEntry` 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-93" * >COMPRESS-93</a>. */ @Test public void testCompressionMethod() throws Exception {
/** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-93" * >COMPRESS-93</a>. */
47
org.apache.commons.compress.archivers.zip.ZipArchiveEntry
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.compress.archivers.zip; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.EntryStreamOffsets; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.zip.ZipException; public class ZipArchiveEntry extends java.util.zip.ZipEntry implements ArchiveEntry, EntryStreamOffsets { public static final int PLATFORM_UNIX = 3; public static final int PLATFORM_FAT = 0; public static final int CRC_UNKNOWN = -1; private static final int SHORT_MASK = 0xFFFF; private static final int SHORT_SHIFT = 16; private static final byte[] EMPTY = new byte[0]; private int method = ZipMethod.UNKNOWN_CODE; private long size = SIZE_UNKNOWN; private int internalAttributes = 0; private int versionRequired; private int versionMadeBy; private int platform = PLATFORM_FAT; private int rawFlag; private long externalAttributes = 0; private int alignment = 0; private ZipExtraField[] extraFields; private UnparseableExtraFieldData unparseableExtra = null; private String name = null; private byte[] rawName = null; private GeneralPurposeBit gpb = new GeneralPurposeBit(); private static final ZipExtraField[] noExtraFields = new ZipExtraField[0]; private long localHeaderOffset = OFFSET_UNKNOWN; private long dataOffset = OFFSET_UNKNOWN; private boolean isStreamContiguous = false; private NameSource nameSource = NameSource.NAME; private CommentSource commentSource = CommentSource.COMMENT; public ZipArchiveEntry(final String name); public ZipArchiveEntry(final java.util.zip.ZipEntry entry) throws ZipException; public ZipArchiveEntry(final ZipArchiveEntry entry) throws ZipException; protected ZipArchiveEntry(); public ZipArchiveEntry(final File inputFile, final String entryName); @Override public Object clone(); @Override public int getMethod(); @Override public void setMethod(final int method); public int getInternalAttributes(); public void setInternalAttributes(final int value); public long getExternalAttributes(); public void setExternalAttributes(final long value); public void setUnixMode(final int mode); public int getUnixMode(); public boolean isUnixSymlink(); public int getPlatform(); protected void setPlatform(final int platform); protected int getAlignment(); public void setAlignment(int alignment); public void setExtraFields(final ZipExtraField[] fields); public ZipExtraField[] getExtraFields(); public ZipExtraField[] getExtraFields(final boolean includeUnparseable); private ZipExtraField[] getParseableExtraFieldsNoCopy(); private ZipExtraField[] getParseableExtraFields(); private ZipExtraField[] getAllExtraFieldsNoCopy(); private ZipExtraField[] copyOf(final ZipExtraField[] src); private ZipExtraField[] copyOf(final ZipExtraField[] src, final int length); private ZipExtraField[] getMergedFields(); private ZipExtraField[] getUnparseableOnly(); private ZipExtraField[] getAllExtraFields(); public void addExtraField(final ZipExtraField ze); public void addAsFirstExtraField(final ZipExtraField ze); public void removeExtraField(final ZipShort type); public void removeUnparseableExtraFieldData(); public ZipExtraField getExtraField(final ZipShort type); public UnparseableExtraFieldData getUnparseableExtraFieldData(); @Override public void setExtra(final byte[] extra) throws RuntimeException; protected void setExtra(); public void setCentralDirectoryExtra(final byte[] b); public byte[] getLocalFileDataExtra(); public byte[] getCentralDirectoryExtra(); @Override public String getName(); @Override public boolean isDirectory(); protected void setName(String name); @Override public long getSize(); @Override public void setSize(final long size); protected void setName(final String name, final byte[] rawName); public byte[] getRawName(); protected long getLocalHeaderOffset(); protected void setLocalHeaderOffset(long localHeaderOffset); @Override public long getDataOffset(); protected void setDataOffset(long dataOffset); @Override public boolean isStreamContiguous(); protected void setStreamContiguous(boolean isStreamContiguous); @Override public int hashCode(); public GeneralPurposeBit getGeneralPurposeBit(); public void setGeneralPurposeBit(final GeneralPurposeBit b); private void mergeExtraFields(final ZipExtraField[] f, final boolean local) throws ZipException; @Override public Date getLastModifiedDate(); @Override public boolean equals(final Object obj); public void setVersionMadeBy(final int versionMadeBy); public void setVersionRequired(final int versionRequired); public int getVersionRequired(); public int getVersionMadeBy(); public int getRawFlag(); public void setRawFlag(final int rawFlag); public NameSource getNameSource(); public void setNameSource(NameSource nameSource); public CommentSource getCommentSource(); public void setCommentSource(CommentSource commentSource); } // Abstract Java Test Class package org.apache.commons.compress.archivers.zip; import static org.apache.commons.compress.AbstractTestCase.getFile; import static org.junit.Assert.*; import java.io.ByteArrayOutputStream; import java.util.zip.ZipEntry; import org.junit.Test; public class ZipArchiveEntryTest { @Test public void testExtraFields(); @Test public void testExtraFieldMerging(); @Test public void testAddAsFirstExtraField(); @Test public void testUnixMode(); @Test public void testCompressionMethod() throws Exception; @Test public void testNotEquals(); @Test public void testNullCommentEqualsEmptyComment(); @Test public void testCopyConstructor() throws Exception; @Test public void isUnixSymlinkIsFalseIfMoreThanOneFlagIsSet() throws Exception; @Test public void testIsUnixSymlink(); } ``` You are a professional Java test case writer, please create a test case named `testCompressionMethod` for the `ZipArchiveEntry` 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-93" * >COMPRESS-93</a>. */ @Test public void testCompressionMethod() throws Exception { ```
public class ZipArchiveEntry extends java.util.zip.ZipEntry implements ArchiveEntry, EntryStreamOffsets
package org.apache.commons.compress.archivers.zip; import static org.apache.commons.compress.AbstractTestCase.getFile; import static org.junit.Assert.*; import java.io.ByteArrayOutputStream; import java.util.zip.ZipEntry; import org.junit.Test;
@Test public void testExtraFields(); @Test public void testExtraFieldMerging(); @Test public void testAddAsFirstExtraField(); @Test public void testUnixMode(); @Test public void testCompressionMethod() throws Exception; @Test public void testNotEquals(); @Test public void testNullCommentEqualsEmptyComment(); @Test public void testCopyConstructor() throws Exception; @Test public void isUnixSymlinkIsFalseIfMoreThanOneFlagIsSet() throws Exception; @Test public void testIsUnixSymlink();
6486332745860952d3c36804e879a4ccbb5baa8dc1a36b573636c642c57abdad
[ "org.apache.commons.compress.archivers.zip.ZipArchiveEntryTest::testCompressionMethod" ]
public static final int PLATFORM_UNIX = 3; public static final int PLATFORM_FAT = 0; public static final int CRC_UNKNOWN = -1; private static final int SHORT_MASK = 0xFFFF; private static final int SHORT_SHIFT = 16; private static final byte[] EMPTY = new byte[0]; private int method = ZipMethod.UNKNOWN_CODE; private long size = SIZE_UNKNOWN; private int internalAttributes = 0; private int versionRequired; private int versionMadeBy; private int platform = PLATFORM_FAT; private int rawFlag; private long externalAttributes = 0; private int alignment = 0; private ZipExtraField[] extraFields; private UnparseableExtraFieldData unparseableExtra = null; private String name = null; private byte[] rawName = null; private GeneralPurposeBit gpb = new GeneralPurposeBit(); private static final ZipExtraField[] noExtraFields = new ZipExtraField[0]; private long localHeaderOffset = OFFSET_UNKNOWN; private long dataOffset = OFFSET_UNKNOWN; private boolean isStreamContiguous = false; private NameSource nameSource = NameSource.NAME; private CommentSource commentSource = CommentSource.COMMENT;
@Test public void testCompressionMethod() 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.*; import java.io.ByteArrayOutputStream; import java.util.zip.ZipEntry; import org.junit.Test; /** * JUnit testcases for org.apache.commons.compress.archivers.zip.ZipEntry. * */ public class ZipArchiveEntryTest { /** * test handling of extra fields */ @Test public void testExtraFields() { final AsiExtraField a = new AsiExtraField(); a.setDirectory(true); a.setMode(0755); final UnrecognizedExtraField u = new UnrecognizedExtraField(); u.setHeaderId(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); u.setLocalFileDataData(new byte[0]); final ZipArchiveEntry ze = new ZipArchiveEntry("test/"); ze.setExtraFields(new ZipExtraField[] {a, u}); final byte[] data1 = ze.getExtra(); ZipExtraField[] result = ze.getExtraFields(); assertEquals("first pass", 2, result.length); assertSame(a, result[0]); assertSame(u, result[1]); final UnrecognizedExtraField u2 = new UnrecognizedExtraField(); u2.setHeaderId(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); u2.setLocalFileDataData(new byte[] {1}); ze.addExtraField(u2); final byte[] data2 = ze.getExtra(); result = ze.getExtraFields(); assertEquals("second pass", 2, result.length); assertSame(a, result[0]); assertSame(u2, result[1]); assertEquals("length second pass", data1.length+1, data2.length); final UnrecognizedExtraField u3 = new UnrecognizedExtraField(); u3.setHeaderId(new ZipShort(2)); u3.setLocalFileDataData(new byte[] {1}); ze.addExtraField(u3); result = ze.getExtraFields(); assertEquals("third pass", 3, result.length); ze.removeExtraField(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); final byte[] data3 = ze.getExtra(); result = ze.getExtraFields(); assertEquals("fourth pass", 2, result.length); assertSame(a, result[0]); assertSame(u3, result[1]); assertEquals("length fourth pass", data2.length, data3.length); try { ze.removeExtraField(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); fail("should be no such element"); } catch (final java.util.NoSuchElementException nse) { } } /** * test handling of extra fields via central directory */ @Test public void testExtraFieldMerging() { final AsiExtraField a = new AsiExtraField(); a.setDirectory(true); a.setMode(0755); final UnrecognizedExtraField u = new UnrecognizedExtraField(); u.setHeaderId(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); u.setLocalFileDataData(new byte[0]); final ZipArchiveEntry ze = new ZipArchiveEntry("test/"); ze.setExtraFields(new ZipExtraField[] {a, u}); // merge // Header-ID 1 + length 1 + one byte of data final byte[] b = ExtraFieldUtilsTest.UNRECOGNIZED_HEADER.getBytes(); ze.setCentralDirectoryExtra(new byte[] {b[0], b[1], 1, 0, 127}); ZipExtraField[] result = ze.getExtraFields(); assertEquals("first pass", 2, result.length); assertSame(a, result[0]); assertEquals(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER, result[1].getHeaderId()); assertEquals(new ZipShort(0), result[1].getLocalFileDataLength()); assertEquals(new ZipShort(1), result[1].getCentralDirectoryLength()); // add new // Header-ID 2 + length 0 ze.setCentralDirectoryExtra(new byte[] {2, 0, 0, 0}); result = ze.getExtraFields(); assertEquals("second pass", 3, result.length); // merge // Header-ID 2 + length 1 + one byte of data ze.setExtra(new byte[] {2, 0, 1, 0, 127}); result = ze.getExtraFields(); assertEquals("third pass", 3, result.length); assertSame(a, result[0]); assertEquals(new ZipShort(2), result[2].getHeaderId()); assertEquals(new ZipShort(1), result[2].getLocalFileDataLength()); assertEquals(new ZipShort(0), result[2].getCentralDirectoryLength()); } /** * test handling of extra fields */ @Test public void testAddAsFirstExtraField() { final AsiExtraField a = new AsiExtraField(); a.setDirectory(true); a.setMode(0755); final UnrecognizedExtraField u = new UnrecognizedExtraField(); u.setHeaderId(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); u.setLocalFileDataData(new byte[0]); final ZipArchiveEntry ze = new ZipArchiveEntry("test/"); ze.setExtraFields(new ZipExtraField[] {a, u}); final byte[] data1 = ze.getExtra(); final UnrecognizedExtraField u2 = new UnrecognizedExtraField(); u2.setHeaderId(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); u2.setLocalFileDataData(new byte[] {1}); ze.addAsFirstExtraField(u2); final byte[] data2 = ze.getExtra(); ZipExtraField[] result = ze.getExtraFields(); assertEquals("second pass", 2, result.length); assertSame(u2, result[0]); assertSame(a, result[1]); assertEquals("length second pass", data1.length + 1, data2.length); final UnrecognizedExtraField u3 = new UnrecognizedExtraField(); u3.setHeaderId(new ZipShort(2)); u3.setLocalFileDataData(new byte[] {1}); ze.addAsFirstExtraField(u3); result = ze.getExtraFields(); assertEquals("third pass", 3, result.length); assertSame(u3, result[0]); assertSame(u2, result[1]); assertSame(a, result[2]); } @Test public void testUnixMode() { ZipArchiveEntry ze = new ZipArchiveEntry("foo"); assertEquals(0, ze.getPlatform()); ze.setUnixMode(0755); assertEquals(3, ze.getPlatform()); assertEquals(0755, (ze.getExternalAttributes() >> 16) & 0xFFFF); assertEquals(0, ze.getExternalAttributes() & 0xFFFF); ze.setUnixMode(0444); assertEquals(3, ze.getPlatform()); assertEquals(0444, (ze.getExternalAttributes() >> 16) & 0xFFFF); assertEquals(1, ze.getExternalAttributes() & 0xFFFF); ze = new ZipArchiveEntry("foo/"); assertEquals(0, ze.getPlatform()); ze.setUnixMode(0777); assertEquals(3, ze.getPlatform()); assertEquals(0777, (ze.getExternalAttributes() >> 16) & 0xFFFF); assertEquals(0x10, ze.getExternalAttributes() & 0xFFFF); ze.setUnixMode(0577); assertEquals(3, ze.getPlatform()); assertEquals(0577, (ze.getExternalAttributes() >> 16) & 0xFFFF); assertEquals(0x11, ze.getExternalAttributes() & 0xFFFF); } /** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-93" * >COMPRESS-93</a>. */ @Test public void testCompressionMethod() throws Exception { final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new ByteArrayOutputStream()); final ZipArchiveEntry entry = new ZipArchiveEntry("foo"); assertEquals(-1, entry.getMethod()); assertFalse(zos.canWriteEntryData(entry)); entry.setMethod(ZipEntry.STORED); assertEquals(ZipEntry.STORED, entry.getMethod()); assertTrue(zos.canWriteEntryData(entry)); entry.setMethod(ZipEntry.DEFLATED); assertEquals(ZipEntry.DEFLATED, entry.getMethod()); assertTrue(zos.canWriteEntryData(entry)); // Test the unsupported "imploded" compression method (6) entry.setMethod(6); assertEquals(6, entry.getMethod()); assertFalse(zos.canWriteEntryData(entry)); zos.close(); } /** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-94" * >COMPRESS-94</a>. */ @Test public void testNotEquals() { final ZipArchiveEntry entry1 = new ZipArchiveEntry("foo"); final ZipArchiveEntry entry2 = new ZipArchiveEntry("bar"); assertFalse(entry1.equals(entry2)); } /** * Tests comment's influence on equals comparisons. * @see "https://issues.apache.org/jira/browse/COMPRESS-187" */ @Test public void testNullCommentEqualsEmptyComment() { final ZipArchiveEntry entry1 = new ZipArchiveEntry("foo"); final ZipArchiveEntry entry2 = new ZipArchiveEntry("foo"); final ZipArchiveEntry entry3 = new ZipArchiveEntry("foo"); entry1.setComment(null); entry2.setComment(""); entry3.setComment("bar"); assertEquals(entry1, entry2); assertFalse(entry1.equals(entry3)); assertFalse(entry2.equals(entry3)); } @Test public void testCopyConstructor() throws Exception { final ZipArchiveEntry archiveEntry = new ZipArchiveEntry("fred"); archiveEntry.setUnixMode(0664); archiveEntry.setMethod(ZipEntry.DEFLATED); archiveEntry.getGeneralPurposeBit().useStrongEncryption(true); final ZipArchiveEntry copy = new ZipArchiveEntry(archiveEntry); assertEquals(archiveEntry, copy); } /** * @see "https://issues.apache.org/jira/browse/COMPRESS-379" */ @Test public void isUnixSymlinkIsFalseIfMoreThanOneFlagIsSet() throws Exception { try (ZipFile zf = new ZipFile(getFile("COMPRESS-379.jar"))) { ZipArchiveEntry ze = zf.getEntry("META-INF/maven/"); assertFalse(ze.isUnixSymlink()); } } @Test public void testIsUnixSymlink() { ZipArchiveEntry ze = new ZipArchiveEntry("foo"); ze.setUnixMode(UnixStat.LINK_FLAG); assertTrue(ze.isUnixSymlink()); ze.setUnixMode(UnixStat.LINK_FLAG | UnixStat.DIR_FLAG); assertFalse(ze.isUnixSymlink()); } }
[ { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveEntry", "be_test_function_name": "getGeneralPurposeBit", "be_test_function_signature": "()Lorg/apache/commons/compress/archivers/zip/GeneralPurposeBit;", "line_numbers": [ "815" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveEntry", "be_test_function_name": "getMethod", "be_test_function_signature": "()I", "line_numbers": [ "258" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveEntry", "be_test_function_name": "getPlatform", "be_test_function_signature": "()I", "line_numbers": [ "364" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveEntry", "be_test_function_name": "setMethod", "be_test_function_signature": "(I)V", "line_numbers": [ "270", "271", "274", "275" ], "method_line_rate": 0.75 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveEntry", "be_test_function_name": "setName", "be_test_function_signature": "(Ljava/lang/String;)V", "line_numbers": [ "695", "697", "699", "700" ], "method_line_rate": 1 } ]
public class ZipArchiveEntryTest
@Test public void testNullCommentEqualsEmptyComment() { final ZipArchiveEntry entry1 = new ZipArchiveEntry("foo"); final ZipArchiveEntry entry2 = new ZipArchiveEntry("foo"); final ZipArchiveEntry entry3 = new ZipArchiveEntry("foo"); entry1.setComment(null); entry2.setComment(""); entry3.setComment("bar"); assertEquals(entry1, entry2); assertFalse(entry1.equals(entry3)); assertFalse(entry2.equals(entry3)); }
// // Abstract Java Tested Class // package org.apache.commons.compress.archivers.zip; // // import org.apache.commons.compress.archivers.ArchiveEntry; // import org.apache.commons.compress.archivers.EntryStreamOffsets; // import java.io.File; // import java.util.ArrayList; // import java.util.Arrays; // import java.util.Date; // import java.util.List; // import java.util.zip.ZipException; // // // // public class ZipArchiveEntry extends java.util.zip.ZipEntry // implements ArchiveEntry, EntryStreamOffsets // { // public static final int PLATFORM_UNIX = 3; // public static final int PLATFORM_FAT = 0; // public static final int CRC_UNKNOWN = -1; // private static final int SHORT_MASK = 0xFFFF; // private static final int SHORT_SHIFT = 16; // private static final byte[] EMPTY = new byte[0]; // private int method = ZipMethod.UNKNOWN_CODE; // private long size = SIZE_UNKNOWN; // private int internalAttributes = 0; // private int versionRequired; // private int versionMadeBy; // private int platform = PLATFORM_FAT; // private int rawFlag; // private long externalAttributes = 0; // private int alignment = 0; // private ZipExtraField[] extraFields; // private UnparseableExtraFieldData unparseableExtra = null; // private String name = null; // private byte[] rawName = null; // private GeneralPurposeBit gpb = new GeneralPurposeBit(); // private static final ZipExtraField[] noExtraFields = new ZipExtraField[0]; // private long localHeaderOffset = OFFSET_UNKNOWN; // private long dataOffset = OFFSET_UNKNOWN; // private boolean isStreamContiguous = false; // private NameSource nameSource = NameSource.NAME; // private CommentSource commentSource = CommentSource.COMMENT; // // public ZipArchiveEntry(final String name); // public ZipArchiveEntry(final java.util.zip.ZipEntry entry) throws ZipException; // public ZipArchiveEntry(final ZipArchiveEntry entry) throws ZipException; // protected ZipArchiveEntry(); // public ZipArchiveEntry(final File inputFile, final String entryName); // @Override // public Object clone(); // @Override // public int getMethod(); // @Override // public void setMethod(final int method); // public int getInternalAttributes(); // public void setInternalAttributes(final int value); // public long getExternalAttributes(); // public void setExternalAttributes(final long value); // public void setUnixMode(final int mode); // public int getUnixMode(); // public boolean isUnixSymlink(); // public int getPlatform(); // protected void setPlatform(final int platform); // protected int getAlignment(); // public void setAlignment(int alignment); // public void setExtraFields(final ZipExtraField[] fields); // public ZipExtraField[] getExtraFields(); // public ZipExtraField[] getExtraFields(final boolean includeUnparseable); // private ZipExtraField[] getParseableExtraFieldsNoCopy(); // private ZipExtraField[] getParseableExtraFields(); // private ZipExtraField[] getAllExtraFieldsNoCopy(); // private ZipExtraField[] copyOf(final ZipExtraField[] src); // private ZipExtraField[] copyOf(final ZipExtraField[] src, final int length); // private ZipExtraField[] getMergedFields(); // private ZipExtraField[] getUnparseableOnly(); // private ZipExtraField[] getAllExtraFields(); // public void addExtraField(final ZipExtraField ze); // public void addAsFirstExtraField(final ZipExtraField ze); // public void removeExtraField(final ZipShort type); // public void removeUnparseableExtraFieldData(); // public ZipExtraField getExtraField(final ZipShort type); // public UnparseableExtraFieldData getUnparseableExtraFieldData(); // @Override // public void setExtra(final byte[] extra) throws RuntimeException; // protected void setExtra(); // public void setCentralDirectoryExtra(final byte[] b); // public byte[] getLocalFileDataExtra(); // public byte[] getCentralDirectoryExtra(); // @Override // public String getName(); // @Override // public boolean isDirectory(); // protected void setName(String name); // @Override // public long getSize(); // @Override // public void setSize(final long size); // protected void setName(final String name, final byte[] rawName); // public byte[] getRawName(); // protected long getLocalHeaderOffset(); // protected void setLocalHeaderOffset(long localHeaderOffset); // @Override // public long getDataOffset(); // protected void setDataOffset(long dataOffset); // @Override // public boolean isStreamContiguous(); // protected void setStreamContiguous(boolean isStreamContiguous); // @Override // public int hashCode(); // public GeneralPurposeBit getGeneralPurposeBit(); // public void setGeneralPurposeBit(final GeneralPurposeBit b); // private void mergeExtraFields(final ZipExtraField[] f, final boolean local) // throws ZipException; // @Override // public Date getLastModifiedDate(); // @Override // public boolean equals(final Object obj); // public void setVersionMadeBy(final int versionMadeBy); // public void setVersionRequired(final int versionRequired); // public int getVersionRequired(); // public int getVersionMadeBy(); // public int getRawFlag(); // public void setRawFlag(final int rawFlag); // public NameSource getNameSource(); // public void setNameSource(NameSource nameSource); // public CommentSource getCommentSource(); // public void setCommentSource(CommentSource commentSource); // } // // // Abstract Java Test Class // package org.apache.commons.compress.archivers.zip; // // import static org.apache.commons.compress.AbstractTestCase.getFile; // import static org.junit.Assert.*; // import java.io.ByteArrayOutputStream; // import java.util.zip.ZipEntry; // import org.junit.Test; // // // // public class ZipArchiveEntryTest { // // // @Test // public void testExtraFields(); // @Test // public void testExtraFieldMerging(); // @Test // public void testAddAsFirstExtraField(); // @Test // public void testUnixMode(); // @Test // public void testCompressionMethod() throws Exception; // @Test // public void testNotEquals(); // @Test // public void testNullCommentEqualsEmptyComment(); // @Test // public void testCopyConstructor() throws Exception; // @Test // public void isUnixSymlinkIsFalseIfMoreThanOneFlagIsSet() throws Exception; // @Test // public void testIsUnixSymlink(); // } // You are a professional Java test case writer, please create a test case named `testNullCommentEqualsEmptyComment` for the `ZipArchiveEntry` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests comment's influence on equals comparisons. * @see "https://issues.apache.org/jira/browse/COMPRESS-187" */
src/test/java/org/apache/commons/compress/archivers/zip/ZipArchiveEntryTest.java
package org.apache.commons.compress.archivers.zip; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.EntryStreamOffsets; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.zip.ZipException;
public ZipArchiveEntry(final String name); public ZipArchiveEntry(final java.util.zip.ZipEntry entry) throws ZipException; public ZipArchiveEntry(final ZipArchiveEntry entry) throws ZipException; protected ZipArchiveEntry(); public ZipArchiveEntry(final File inputFile, final String entryName); @Override public Object clone(); @Override public int getMethod(); @Override public void setMethod(final int method); public int getInternalAttributes(); public void setInternalAttributes(final int value); public long getExternalAttributes(); public void setExternalAttributes(final long value); public void setUnixMode(final int mode); public int getUnixMode(); public boolean isUnixSymlink(); public int getPlatform(); protected void setPlatform(final int platform); protected int getAlignment(); public void setAlignment(int alignment); public void setExtraFields(final ZipExtraField[] fields); public ZipExtraField[] getExtraFields(); public ZipExtraField[] getExtraFields(final boolean includeUnparseable); private ZipExtraField[] getParseableExtraFieldsNoCopy(); private ZipExtraField[] getParseableExtraFields(); private ZipExtraField[] getAllExtraFieldsNoCopy(); private ZipExtraField[] copyOf(final ZipExtraField[] src); private ZipExtraField[] copyOf(final ZipExtraField[] src, final int length); private ZipExtraField[] getMergedFields(); private ZipExtraField[] getUnparseableOnly(); private ZipExtraField[] getAllExtraFields(); public void addExtraField(final ZipExtraField ze); public void addAsFirstExtraField(final ZipExtraField ze); public void removeExtraField(final ZipShort type); public void removeUnparseableExtraFieldData(); public ZipExtraField getExtraField(final ZipShort type); public UnparseableExtraFieldData getUnparseableExtraFieldData(); @Override public void setExtra(final byte[] extra) throws RuntimeException; protected void setExtra(); public void setCentralDirectoryExtra(final byte[] b); public byte[] getLocalFileDataExtra(); public byte[] getCentralDirectoryExtra(); @Override public String getName(); @Override public boolean isDirectory(); protected void setName(String name); @Override public long getSize(); @Override public void setSize(final long size); protected void setName(final String name, final byte[] rawName); public byte[] getRawName(); protected long getLocalHeaderOffset(); protected void setLocalHeaderOffset(long localHeaderOffset); @Override public long getDataOffset(); protected void setDataOffset(long dataOffset); @Override public boolean isStreamContiguous(); protected void setStreamContiguous(boolean isStreamContiguous); @Override public int hashCode(); public GeneralPurposeBit getGeneralPurposeBit(); public void setGeneralPurposeBit(final GeneralPurposeBit b); private void mergeExtraFields(final ZipExtraField[] f, final boolean local) throws ZipException; @Override public Date getLastModifiedDate(); @Override public boolean equals(final Object obj); public void setVersionMadeBy(final int versionMadeBy); public void setVersionRequired(final int versionRequired); public int getVersionRequired(); public int getVersionMadeBy(); public int getRawFlag(); public void setRawFlag(final int rawFlag); public NameSource getNameSource(); public void setNameSource(NameSource nameSource); public CommentSource getCommentSource(); public void setCommentSource(CommentSource commentSource);
260
testNullCommentEqualsEmptyComment
```java // Abstract Java Tested Class package org.apache.commons.compress.archivers.zip; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.EntryStreamOffsets; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.zip.ZipException; public class ZipArchiveEntry extends java.util.zip.ZipEntry implements ArchiveEntry, EntryStreamOffsets { public static final int PLATFORM_UNIX = 3; public static final int PLATFORM_FAT = 0; public static final int CRC_UNKNOWN = -1; private static final int SHORT_MASK = 0xFFFF; private static final int SHORT_SHIFT = 16; private static final byte[] EMPTY = new byte[0]; private int method = ZipMethod.UNKNOWN_CODE; private long size = SIZE_UNKNOWN; private int internalAttributes = 0; private int versionRequired; private int versionMadeBy; private int platform = PLATFORM_FAT; private int rawFlag; private long externalAttributes = 0; private int alignment = 0; private ZipExtraField[] extraFields; private UnparseableExtraFieldData unparseableExtra = null; private String name = null; private byte[] rawName = null; private GeneralPurposeBit gpb = new GeneralPurposeBit(); private static final ZipExtraField[] noExtraFields = new ZipExtraField[0]; private long localHeaderOffset = OFFSET_UNKNOWN; private long dataOffset = OFFSET_UNKNOWN; private boolean isStreamContiguous = false; private NameSource nameSource = NameSource.NAME; private CommentSource commentSource = CommentSource.COMMENT; public ZipArchiveEntry(final String name); public ZipArchiveEntry(final java.util.zip.ZipEntry entry) throws ZipException; public ZipArchiveEntry(final ZipArchiveEntry entry) throws ZipException; protected ZipArchiveEntry(); public ZipArchiveEntry(final File inputFile, final String entryName); @Override public Object clone(); @Override public int getMethod(); @Override public void setMethod(final int method); public int getInternalAttributes(); public void setInternalAttributes(final int value); public long getExternalAttributes(); public void setExternalAttributes(final long value); public void setUnixMode(final int mode); public int getUnixMode(); public boolean isUnixSymlink(); public int getPlatform(); protected void setPlatform(final int platform); protected int getAlignment(); public void setAlignment(int alignment); public void setExtraFields(final ZipExtraField[] fields); public ZipExtraField[] getExtraFields(); public ZipExtraField[] getExtraFields(final boolean includeUnparseable); private ZipExtraField[] getParseableExtraFieldsNoCopy(); private ZipExtraField[] getParseableExtraFields(); private ZipExtraField[] getAllExtraFieldsNoCopy(); private ZipExtraField[] copyOf(final ZipExtraField[] src); private ZipExtraField[] copyOf(final ZipExtraField[] src, final int length); private ZipExtraField[] getMergedFields(); private ZipExtraField[] getUnparseableOnly(); private ZipExtraField[] getAllExtraFields(); public void addExtraField(final ZipExtraField ze); public void addAsFirstExtraField(final ZipExtraField ze); public void removeExtraField(final ZipShort type); public void removeUnparseableExtraFieldData(); public ZipExtraField getExtraField(final ZipShort type); public UnparseableExtraFieldData getUnparseableExtraFieldData(); @Override public void setExtra(final byte[] extra) throws RuntimeException; protected void setExtra(); public void setCentralDirectoryExtra(final byte[] b); public byte[] getLocalFileDataExtra(); public byte[] getCentralDirectoryExtra(); @Override public String getName(); @Override public boolean isDirectory(); protected void setName(String name); @Override public long getSize(); @Override public void setSize(final long size); protected void setName(final String name, final byte[] rawName); public byte[] getRawName(); protected long getLocalHeaderOffset(); protected void setLocalHeaderOffset(long localHeaderOffset); @Override public long getDataOffset(); protected void setDataOffset(long dataOffset); @Override public boolean isStreamContiguous(); protected void setStreamContiguous(boolean isStreamContiguous); @Override public int hashCode(); public GeneralPurposeBit getGeneralPurposeBit(); public void setGeneralPurposeBit(final GeneralPurposeBit b); private void mergeExtraFields(final ZipExtraField[] f, final boolean local) throws ZipException; @Override public Date getLastModifiedDate(); @Override public boolean equals(final Object obj); public void setVersionMadeBy(final int versionMadeBy); public void setVersionRequired(final int versionRequired); public int getVersionRequired(); public int getVersionMadeBy(); public int getRawFlag(); public void setRawFlag(final int rawFlag); public NameSource getNameSource(); public void setNameSource(NameSource nameSource); public CommentSource getCommentSource(); public void setCommentSource(CommentSource commentSource); } // Abstract Java Test Class package org.apache.commons.compress.archivers.zip; import static org.apache.commons.compress.AbstractTestCase.getFile; import static org.junit.Assert.*; import java.io.ByteArrayOutputStream; import java.util.zip.ZipEntry; import org.junit.Test; public class ZipArchiveEntryTest { @Test public void testExtraFields(); @Test public void testExtraFieldMerging(); @Test public void testAddAsFirstExtraField(); @Test public void testUnixMode(); @Test public void testCompressionMethod() throws Exception; @Test public void testNotEquals(); @Test public void testNullCommentEqualsEmptyComment(); @Test public void testCopyConstructor() throws Exception; @Test public void isUnixSymlinkIsFalseIfMoreThanOneFlagIsSet() throws Exception; @Test public void testIsUnixSymlink(); } ``` You are a professional Java test case writer, please create a test case named `testNullCommentEqualsEmptyComment` for the `ZipArchiveEntry` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests comment's influence on equals comparisons. * @see "https://issues.apache.org/jira/browse/COMPRESS-187" */
249
// // Abstract Java Tested Class // package org.apache.commons.compress.archivers.zip; // // import org.apache.commons.compress.archivers.ArchiveEntry; // import org.apache.commons.compress.archivers.EntryStreamOffsets; // import java.io.File; // import java.util.ArrayList; // import java.util.Arrays; // import java.util.Date; // import java.util.List; // import java.util.zip.ZipException; // // // // public class ZipArchiveEntry extends java.util.zip.ZipEntry // implements ArchiveEntry, EntryStreamOffsets // { // public static final int PLATFORM_UNIX = 3; // public static final int PLATFORM_FAT = 0; // public static final int CRC_UNKNOWN = -1; // private static final int SHORT_MASK = 0xFFFF; // private static final int SHORT_SHIFT = 16; // private static final byte[] EMPTY = new byte[0]; // private int method = ZipMethod.UNKNOWN_CODE; // private long size = SIZE_UNKNOWN; // private int internalAttributes = 0; // private int versionRequired; // private int versionMadeBy; // private int platform = PLATFORM_FAT; // private int rawFlag; // private long externalAttributes = 0; // private int alignment = 0; // private ZipExtraField[] extraFields; // private UnparseableExtraFieldData unparseableExtra = null; // private String name = null; // private byte[] rawName = null; // private GeneralPurposeBit gpb = new GeneralPurposeBit(); // private static final ZipExtraField[] noExtraFields = new ZipExtraField[0]; // private long localHeaderOffset = OFFSET_UNKNOWN; // private long dataOffset = OFFSET_UNKNOWN; // private boolean isStreamContiguous = false; // private NameSource nameSource = NameSource.NAME; // private CommentSource commentSource = CommentSource.COMMENT; // // public ZipArchiveEntry(final String name); // public ZipArchiveEntry(final java.util.zip.ZipEntry entry) throws ZipException; // public ZipArchiveEntry(final ZipArchiveEntry entry) throws ZipException; // protected ZipArchiveEntry(); // public ZipArchiveEntry(final File inputFile, final String entryName); // @Override // public Object clone(); // @Override // public int getMethod(); // @Override // public void setMethod(final int method); // public int getInternalAttributes(); // public void setInternalAttributes(final int value); // public long getExternalAttributes(); // public void setExternalAttributes(final long value); // public void setUnixMode(final int mode); // public int getUnixMode(); // public boolean isUnixSymlink(); // public int getPlatform(); // protected void setPlatform(final int platform); // protected int getAlignment(); // public void setAlignment(int alignment); // public void setExtraFields(final ZipExtraField[] fields); // public ZipExtraField[] getExtraFields(); // public ZipExtraField[] getExtraFields(final boolean includeUnparseable); // private ZipExtraField[] getParseableExtraFieldsNoCopy(); // private ZipExtraField[] getParseableExtraFields(); // private ZipExtraField[] getAllExtraFieldsNoCopy(); // private ZipExtraField[] copyOf(final ZipExtraField[] src); // private ZipExtraField[] copyOf(final ZipExtraField[] src, final int length); // private ZipExtraField[] getMergedFields(); // private ZipExtraField[] getUnparseableOnly(); // private ZipExtraField[] getAllExtraFields(); // public void addExtraField(final ZipExtraField ze); // public void addAsFirstExtraField(final ZipExtraField ze); // public void removeExtraField(final ZipShort type); // public void removeUnparseableExtraFieldData(); // public ZipExtraField getExtraField(final ZipShort type); // public UnparseableExtraFieldData getUnparseableExtraFieldData(); // @Override // public void setExtra(final byte[] extra) throws RuntimeException; // protected void setExtra(); // public void setCentralDirectoryExtra(final byte[] b); // public byte[] getLocalFileDataExtra(); // public byte[] getCentralDirectoryExtra(); // @Override // public String getName(); // @Override // public boolean isDirectory(); // protected void setName(String name); // @Override // public long getSize(); // @Override // public void setSize(final long size); // protected void setName(final String name, final byte[] rawName); // public byte[] getRawName(); // protected long getLocalHeaderOffset(); // protected void setLocalHeaderOffset(long localHeaderOffset); // @Override // public long getDataOffset(); // protected void setDataOffset(long dataOffset); // @Override // public boolean isStreamContiguous(); // protected void setStreamContiguous(boolean isStreamContiguous); // @Override // public int hashCode(); // public GeneralPurposeBit getGeneralPurposeBit(); // public void setGeneralPurposeBit(final GeneralPurposeBit b); // private void mergeExtraFields(final ZipExtraField[] f, final boolean local) // throws ZipException; // @Override // public Date getLastModifiedDate(); // @Override // public boolean equals(final Object obj); // public void setVersionMadeBy(final int versionMadeBy); // public void setVersionRequired(final int versionRequired); // public int getVersionRequired(); // public int getVersionMadeBy(); // public int getRawFlag(); // public void setRawFlag(final int rawFlag); // public NameSource getNameSource(); // public void setNameSource(NameSource nameSource); // public CommentSource getCommentSource(); // public void setCommentSource(CommentSource commentSource); // } // // // Abstract Java Test Class // package org.apache.commons.compress.archivers.zip; // // import static org.apache.commons.compress.AbstractTestCase.getFile; // import static org.junit.Assert.*; // import java.io.ByteArrayOutputStream; // import java.util.zip.ZipEntry; // import org.junit.Test; // // // // public class ZipArchiveEntryTest { // // // @Test // public void testExtraFields(); // @Test // public void testExtraFieldMerging(); // @Test // public void testAddAsFirstExtraField(); // @Test // public void testUnixMode(); // @Test // public void testCompressionMethod() throws Exception; // @Test // public void testNotEquals(); // @Test // public void testNullCommentEqualsEmptyComment(); // @Test // public void testCopyConstructor() throws Exception; // @Test // public void isUnixSymlinkIsFalseIfMoreThanOneFlagIsSet() throws Exception; // @Test // public void testIsUnixSymlink(); // } // You are a professional Java test case writer, please create a test case named `testNullCommentEqualsEmptyComment` for the `ZipArchiveEntry` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests comment's influence on equals comparisons. * @see "https://issues.apache.org/jira/browse/COMPRESS-187" */ @Test public void testNullCommentEqualsEmptyComment() {
/** * Tests comment's influence on equals comparisons. * @see "https://issues.apache.org/jira/browse/COMPRESS-187" */
47
org.apache.commons.compress.archivers.zip.ZipArchiveEntry
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.compress.archivers.zip; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.EntryStreamOffsets; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.zip.ZipException; public class ZipArchiveEntry extends java.util.zip.ZipEntry implements ArchiveEntry, EntryStreamOffsets { public static final int PLATFORM_UNIX = 3; public static final int PLATFORM_FAT = 0; public static final int CRC_UNKNOWN = -1; private static final int SHORT_MASK = 0xFFFF; private static final int SHORT_SHIFT = 16; private static final byte[] EMPTY = new byte[0]; private int method = ZipMethod.UNKNOWN_CODE; private long size = SIZE_UNKNOWN; private int internalAttributes = 0; private int versionRequired; private int versionMadeBy; private int platform = PLATFORM_FAT; private int rawFlag; private long externalAttributes = 0; private int alignment = 0; private ZipExtraField[] extraFields; private UnparseableExtraFieldData unparseableExtra = null; private String name = null; private byte[] rawName = null; private GeneralPurposeBit gpb = new GeneralPurposeBit(); private static final ZipExtraField[] noExtraFields = new ZipExtraField[0]; private long localHeaderOffset = OFFSET_UNKNOWN; private long dataOffset = OFFSET_UNKNOWN; private boolean isStreamContiguous = false; private NameSource nameSource = NameSource.NAME; private CommentSource commentSource = CommentSource.COMMENT; public ZipArchiveEntry(final String name); public ZipArchiveEntry(final java.util.zip.ZipEntry entry) throws ZipException; public ZipArchiveEntry(final ZipArchiveEntry entry) throws ZipException; protected ZipArchiveEntry(); public ZipArchiveEntry(final File inputFile, final String entryName); @Override public Object clone(); @Override public int getMethod(); @Override public void setMethod(final int method); public int getInternalAttributes(); public void setInternalAttributes(final int value); public long getExternalAttributes(); public void setExternalAttributes(final long value); public void setUnixMode(final int mode); public int getUnixMode(); public boolean isUnixSymlink(); public int getPlatform(); protected void setPlatform(final int platform); protected int getAlignment(); public void setAlignment(int alignment); public void setExtraFields(final ZipExtraField[] fields); public ZipExtraField[] getExtraFields(); public ZipExtraField[] getExtraFields(final boolean includeUnparseable); private ZipExtraField[] getParseableExtraFieldsNoCopy(); private ZipExtraField[] getParseableExtraFields(); private ZipExtraField[] getAllExtraFieldsNoCopy(); private ZipExtraField[] copyOf(final ZipExtraField[] src); private ZipExtraField[] copyOf(final ZipExtraField[] src, final int length); private ZipExtraField[] getMergedFields(); private ZipExtraField[] getUnparseableOnly(); private ZipExtraField[] getAllExtraFields(); public void addExtraField(final ZipExtraField ze); public void addAsFirstExtraField(final ZipExtraField ze); public void removeExtraField(final ZipShort type); public void removeUnparseableExtraFieldData(); public ZipExtraField getExtraField(final ZipShort type); public UnparseableExtraFieldData getUnparseableExtraFieldData(); @Override public void setExtra(final byte[] extra) throws RuntimeException; protected void setExtra(); public void setCentralDirectoryExtra(final byte[] b); public byte[] getLocalFileDataExtra(); public byte[] getCentralDirectoryExtra(); @Override public String getName(); @Override public boolean isDirectory(); protected void setName(String name); @Override public long getSize(); @Override public void setSize(final long size); protected void setName(final String name, final byte[] rawName); public byte[] getRawName(); protected long getLocalHeaderOffset(); protected void setLocalHeaderOffset(long localHeaderOffset); @Override public long getDataOffset(); protected void setDataOffset(long dataOffset); @Override public boolean isStreamContiguous(); protected void setStreamContiguous(boolean isStreamContiguous); @Override public int hashCode(); public GeneralPurposeBit getGeneralPurposeBit(); public void setGeneralPurposeBit(final GeneralPurposeBit b); private void mergeExtraFields(final ZipExtraField[] f, final boolean local) throws ZipException; @Override public Date getLastModifiedDate(); @Override public boolean equals(final Object obj); public void setVersionMadeBy(final int versionMadeBy); public void setVersionRequired(final int versionRequired); public int getVersionRequired(); public int getVersionMadeBy(); public int getRawFlag(); public void setRawFlag(final int rawFlag); public NameSource getNameSource(); public void setNameSource(NameSource nameSource); public CommentSource getCommentSource(); public void setCommentSource(CommentSource commentSource); } // Abstract Java Test Class package org.apache.commons.compress.archivers.zip; import static org.apache.commons.compress.AbstractTestCase.getFile; import static org.junit.Assert.*; import java.io.ByteArrayOutputStream; import java.util.zip.ZipEntry; import org.junit.Test; public class ZipArchiveEntryTest { @Test public void testExtraFields(); @Test public void testExtraFieldMerging(); @Test public void testAddAsFirstExtraField(); @Test public void testUnixMode(); @Test public void testCompressionMethod() throws Exception; @Test public void testNotEquals(); @Test public void testNullCommentEqualsEmptyComment(); @Test public void testCopyConstructor() throws Exception; @Test public void isUnixSymlinkIsFalseIfMoreThanOneFlagIsSet() throws Exception; @Test public void testIsUnixSymlink(); } ``` You are a professional Java test case writer, please create a test case named `testNullCommentEqualsEmptyComment` for the `ZipArchiveEntry` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests comment's influence on equals comparisons. * @see "https://issues.apache.org/jira/browse/COMPRESS-187" */ @Test public void testNullCommentEqualsEmptyComment() { ```
public class ZipArchiveEntry extends java.util.zip.ZipEntry implements ArchiveEntry, EntryStreamOffsets
package org.apache.commons.compress.archivers.zip; import static org.apache.commons.compress.AbstractTestCase.getFile; import static org.junit.Assert.*; import java.io.ByteArrayOutputStream; import java.util.zip.ZipEntry; import org.junit.Test;
@Test public void testExtraFields(); @Test public void testExtraFieldMerging(); @Test public void testAddAsFirstExtraField(); @Test public void testUnixMode(); @Test public void testCompressionMethod() throws Exception; @Test public void testNotEquals(); @Test public void testNullCommentEqualsEmptyComment(); @Test public void testCopyConstructor() throws Exception; @Test public void isUnixSymlinkIsFalseIfMoreThanOneFlagIsSet() throws Exception; @Test public void testIsUnixSymlink();
650a23b0d29efd0b02d7117e04cfbfd5884ede9e60acf1735942aa7d78740fcf
[ "org.apache.commons.compress.archivers.zip.ZipArchiveEntryTest::testNullCommentEqualsEmptyComment" ]
public static final int PLATFORM_UNIX = 3; public static final int PLATFORM_FAT = 0; public static final int CRC_UNKNOWN = -1; private static final int SHORT_MASK = 0xFFFF; private static final int SHORT_SHIFT = 16; private static final byte[] EMPTY = new byte[0]; private int method = ZipMethod.UNKNOWN_CODE; private long size = SIZE_UNKNOWN; private int internalAttributes = 0; private int versionRequired; private int versionMadeBy; private int platform = PLATFORM_FAT; private int rawFlag; private long externalAttributes = 0; private int alignment = 0; private ZipExtraField[] extraFields; private UnparseableExtraFieldData unparseableExtra = null; private String name = null; private byte[] rawName = null; private GeneralPurposeBit gpb = new GeneralPurposeBit(); private static final ZipExtraField[] noExtraFields = new ZipExtraField[0]; private long localHeaderOffset = OFFSET_UNKNOWN; private long dataOffset = OFFSET_UNKNOWN; private boolean isStreamContiguous = false; private NameSource nameSource = NameSource.NAME; private CommentSource commentSource = CommentSource.COMMENT;
@Test public void testNullCommentEqualsEmptyComment()
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.*; import java.io.ByteArrayOutputStream; import java.util.zip.ZipEntry; import org.junit.Test; /** * JUnit testcases for org.apache.commons.compress.archivers.zip.ZipEntry. * */ public class ZipArchiveEntryTest { /** * test handling of extra fields */ @Test public void testExtraFields() { final AsiExtraField a = new AsiExtraField(); a.setDirectory(true); a.setMode(0755); final UnrecognizedExtraField u = new UnrecognizedExtraField(); u.setHeaderId(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); u.setLocalFileDataData(new byte[0]); final ZipArchiveEntry ze = new ZipArchiveEntry("test/"); ze.setExtraFields(new ZipExtraField[] {a, u}); final byte[] data1 = ze.getExtra(); ZipExtraField[] result = ze.getExtraFields(); assertEquals("first pass", 2, result.length); assertSame(a, result[0]); assertSame(u, result[1]); final UnrecognizedExtraField u2 = new UnrecognizedExtraField(); u2.setHeaderId(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); u2.setLocalFileDataData(new byte[] {1}); ze.addExtraField(u2); final byte[] data2 = ze.getExtra(); result = ze.getExtraFields(); assertEquals("second pass", 2, result.length); assertSame(a, result[0]); assertSame(u2, result[1]); assertEquals("length second pass", data1.length+1, data2.length); final UnrecognizedExtraField u3 = new UnrecognizedExtraField(); u3.setHeaderId(new ZipShort(2)); u3.setLocalFileDataData(new byte[] {1}); ze.addExtraField(u3); result = ze.getExtraFields(); assertEquals("third pass", 3, result.length); ze.removeExtraField(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); final byte[] data3 = ze.getExtra(); result = ze.getExtraFields(); assertEquals("fourth pass", 2, result.length); assertSame(a, result[0]); assertSame(u3, result[1]); assertEquals("length fourth pass", data2.length, data3.length); try { ze.removeExtraField(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); fail("should be no such element"); } catch (final java.util.NoSuchElementException nse) { } } /** * test handling of extra fields via central directory */ @Test public void testExtraFieldMerging() { final AsiExtraField a = new AsiExtraField(); a.setDirectory(true); a.setMode(0755); final UnrecognizedExtraField u = new UnrecognizedExtraField(); u.setHeaderId(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); u.setLocalFileDataData(new byte[0]); final ZipArchiveEntry ze = new ZipArchiveEntry("test/"); ze.setExtraFields(new ZipExtraField[] {a, u}); // merge // Header-ID 1 + length 1 + one byte of data final byte[] b = ExtraFieldUtilsTest.UNRECOGNIZED_HEADER.getBytes(); ze.setCentralDirectoryExtra(new byte[] {b[0], b[1], 1, 0, 127}); ZipExtraField[] result = ze.getExtraFields(); assertEquals("first pass", 2, result.length); assertSame(a, result[0]); assertEquals(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER, result[1].getHeaderId()); assertEquals(new ZipShort(0), result[1].getLocalFileDataLength()); assertEquals(new ZipShort(1), result[1].getCentralDirectoryLength()); // add new // Header-ID 2 + length 0 ze.setCentralDirectoryExtra(new byte[] {2, 0, 0, 0}); result = ze.getExtraFields(); assertEquals("second pass", 3, result.length); // merge // Header-ID 2 + length 1 + one byte of data ze.setExtra(new byte[] {2, 0, 1, 0, 127}); result = ze.getExtraFields(); assertEquals("third pass", 3, result.length); assertSame(a, result[0]); assertEquals(new ZipShort(2), result[2].getHeaderId()); assertEquals(new ZipShort(1), result[2].getLocalFileDataLength()); assertEquals(new ZipShort(0), result[2].getCentralDirectoryLength()); } /** * test handling of extra fields */ @Test public void testAddAsFirstExtraField() { final AsiExtraField a = new AsiExtraField(); a.setDirectory(true); a.setMode(0755); final UnrecognizedExtraField u = new UnrecognizedExtraField(); u.setHeaderId(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); u.setLocalFileDataData(new byte[0]); final ZipArchiveEntry ze = new ZipArchiveEntry("test/"); ze.setExtraFields(new ZipExtraField[] {a, u}); final byte[] data1 = ze.getExtra(); final UnrecognizedExtraField u2 = new UnrecognizedExtraField(); u2.setHeaderId(ExtraFieldUtilsTest.UNRECOGNIZED_HEADER); u2.setLocalFileDataData(new byte[] {1}); ze.addAsFirstExtraField(u2); final byte[] data2 = ze.getExtra(); ZipExtraField[] result = ze.getExtraFields(); assertEquals("second pass", 2, result.length); assertSame(u2, result[0]); assertSame(a, result[1]); assertEquals("length second pass", data1.length + 1, data2.length); final UnrecognizedExtraField u3 = new UnrecognizedExtraField(); u3.setHeaderId(new ZipShort(2)); u3.setLocalFileDataData(new byte[] {1}); ze.addAsFirstExtraField(u3); result = ze.getExtraFields(); assertEquals("third pass", 3, result.length); assertSame(u3, result[0]); assertSame(u2, result[1]); assertSame(a, result[2]); } @Test public void testUnixMode() { ZipArchiveEntry ze = new ZipArchiveEntry("foo"); assertEquals(0, ze.getPlatform()); ze.setUnixMode(0755); assertEquals(3, ze.getPlatform()); assertEquals(0755, (ze.getExternalAttributes() >> 16) & 0xFFFF); assertEquals(0, ze.getExternalAttributes() & 0xFFFF); ze.setUnixMode(0444); assertEquals(3, ze.getPlatform()); assertEquals(0444, (ze.getExternalAttributes() >> 16) & 0xFFFF); assertEquals(1, ze.getExternalAttributes() & 0xFFFF); ze = new ZipArchiveEntry("foo/"); assertEquals(0, ze.getPlatform()); ze.setUnixMode(0777); assertEquals(3, ze.getPlatform()); assertEquals(0777, (ze.getExternalAttributes() >> 16) & 0xFFFF); assertEquals(0x10, ze.getExternalAttributes() & 0xFFFF); ze.setUnixMode(0577); assertEquals(3, ze.getPlatform()); assertEquals(0577, (ze.getExternalAttributes() >> 16) & 0xFFFF); assertEquals(0x11, ze.getExternalAttributes() & 0xFFFF); } /** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-93" * >COMPRESS-93</a>. */ @Test public void testCompressionMethod() throws Exception { final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new ByteArrayOutputStream()); final ZipArchiveEntry entry = new ZipArchiveEntry("foo"); assertEquals(-1, entry.getMethod()); assertFalse(zos.canWriteEntryData(entry)); entry.setMethod(ZipEntry.STORED); assertEquals(ZipEntry.STORED, entry.getMethod()); assertTrue(zos.canWriteEntryData(entry)); entry.setMethod(ZipEntry.DEFLATED); assertEquals(ZipEntry.DEFLATED, entry.getMethod()); assertTrue(zos.canWriteEntryData(entry)); // Test the unsupported "imploded" compression method (6) entry.setMethod(6); assertEquals(6, entry.getMethod()); assertFalse(zos.canWriteEntryData(entry)); zos.close(); } /** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-94" * >COMPRESS-94</a>. */ @Test public void testNotEquals() { final ZipArchiveEntry entry1 = new ZipArchiveEntry("foo"); final ZipArchiveEntry entry2 = new ZipArchiveEntry("bar"); assertFalse(entry1.equals(entry2)); } /** * Tests comment's influence on equals comparisons. * @see "https://issues.apache.org/jira/browse/COMPRESS-187" */ @Test public void testNullCommentEqualsEmptyComment() { final ZipArchiveEntry entry1 = new ZipArchiveEntry("foo"); final ZipArchiveEntry entry2 = new ZipArchiveEntry("foo"); final ZipArchiveEntry entry3 = new ZipArchiveEntry("foo"); entry1.setComment(null); entry2.setComment(""); entry3.setComment("bar"); assertEquals(entry1, entry2); assertFalse(entry1.equals(entry3)); assertFalse(entry2.equals(entry3)); } @Test public void testCopyConstructor() throws Exception { final ZipArchiveEntry archiveEntry = new ZipArchiveEntry("fred"); archiveEntry.setUnixMode(0664); archiveEntry.setMethod(ZipEntry.DEFLATED); archiveEntry.getGeneralPurposeBit().useStrongEncryption(true); final ZipArchiveEntry copy = new ZipArchiveEntry(archiveEntry); assertEquals(archiveEntry, copy); } /** * @see "https://issues.apache.org/jira/browse/COMPRESS-379" */ @Test public void isUnixSymlinkIsFalseIfMoreThanOneFlagIsSet() throws Exception { try (ZipFile zf = new ZipFile(getFile("COMPRESS-379.jar"))) { ZipArchiveEntry ze = zf.getEntry("META-INF/maven/"); assertFalse(ze.isUnixSymlink()); } } @Test public void testIsUnixSymlink() { ZipArchiveEntry ze = new ZipArchiveEntry("foo"); ze.setUnixMode(UnixStat.LINK_FLAG); assertTrue(ze.isUnixSymlink()); ze.setUnixMode(UnixStat.LINK_FLAG | UnixStat.DIR_FLAG); assertFalse(ze.isUnixSymlink()); } }
[ { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveEntry", "be_test_function_name": "equals", "be_test_function_signature": "(Ljava/lang/Object;)Z", "line_numbers": [ "881", "882", "884", "885", "887", "888", "889", "890", "891", "892", "894", "895", "897", "898", "899", "900", "902", "903", "905" ], "method_line_rate": 0.6842105263157895 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveEntry", "be_test_function_name": "getAllExtraFieldsNoCopy", "be_test_function_signature": "()[Lorg/apache/commons/compress/archivers/zip/ZipExtraField;", "line_numbers": [ "464", "465", "467" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveEntry", "be_test_function_name": "getCentralDirectoryExtra", "be_test_function_signature": "()[B", "line_numbers": [ "669" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveEntry", "be_test_function_name": "getExternalAttributes", "be_test_function_signature": "()J", "line_numbers": [ "308" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveEntry", "be_test_function_name": "getInternalAttributes", "be_test_function_signature": "()I", "line_numbers": [ "287" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveEntry", "be_test_function_name": "getLocalFileDataExtra", "be_test_function_signature": "()[B", "line_numbers": [ "660", "661" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveEntry", "be_test_function_name": "getMethod", "be_test_function_signature": "()I", "line_numbers": [ "258" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveEntry", "be_test_function_name": "getName", "be_test_function_signature": "()Ljava/lang/String;", "line_numbers": [ "678" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveEntry", "be_test_function_name": "getPlatform", "be_test_function_signature": "()I", "line_numbers": [ "364" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveEntry", "be_test_function_name": "getSize", "be_test_function_signature": "()J", "line_numbers": [ "713" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveEntry", "be_test_function_name": "getUnparseableOnly", "be_test_function_signature": "()[Lorg/apache/commons/compress/archivers/zip/ZipExtraField;", "line_numbers": [ "487" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipArchiveEntry.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipArchiveEntry", "be_test_function_name": "setName", "be_test_function_signature": "(Ljava/lang/String;)V", "line_numbers": [ "695", "697", "699", "700" ], "method_line_rate": 1 } ]
public class RenamePrototypesTest extends CompilerTestCase
public void testRenameProperties() { test("var foo; foo.prop_='bar'", "var foo;foo.a='bar'"); test("this.prop_='bar'", "this.a='bar'"); test("this.prop='bar'", "this.prop='bar'"); test("this['prop_']='bar'", "this['a']='bar'"); test("this['prop']='bar'", "this['prop']='bar'"); test("var foo={prop1_: 'bar',prop2_: 'baz'};", "var foo={a:'bar',b:'baz'}"); }
// // Abstract Java Tested Class // package com.google.javascript.jscomp; // // import com.google.common.base.Preconditions; // import com.google.common.collect.ImmutableMap; // import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage; // import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback; // import com.google.javascript.rhino.Node; // import com.google.javascript.rhino.Token; // import com.google.javascript.rhino.TokenStream; // import java.util.Arrays; // import java.util.Comparator; // import java.util.HashMap; // import java.util.HashSet; // import java.util.Iterator; // import java.util.Map; // import java.util.Set; // import java.util.SortedSet; // import java.util.TreeSet; // import javax.annotation.Nullable; // // // // class RenamePrototypes implements CompilerPass { // private final AbstractCompiler compiler; // private final boolean aggressiveRenaming; // private final char[] reservedCharacters; // private final VariableMap prevUsedRenameMap; // private static final Comparator<Property> FREQUENCY_COMPARATOR = // new Comparator<Property>() { // @Override // public int compare(Property a1, Property a2) { // int n1 = a1.count(); // int n2 = a2.count(); // if (n1 != n2) { // return n2 - n1; // } // return a1.oldName.compareTo(a2.oldName); // } // }; // private final Set<Node> stringNodes = new HashSet<Node>(); // private final Map<String, Property> properties = // new HashMap<String, Property>(); // private final Set<String> reservedNames = // new HashSet<String>(Arrays.asList( // "indexOf", "lastIndexOf", "toString", "valueOf")); // private final Set<Node> prototypeObjLits = new HashSet<Node>(); // // RenamePrototypes(AbstractCompiler compiler, boolean aggressiveRenaming, // @Nullable char[] reservedCharacters, // @Nullable VariableMap prevUsedRenameMap); // @Override // public void process(Node externs, Node root); // private void reusePrototypeNames(Set<Property> properties); // VariableMap getPropertyMap(); // Property(String name); // int count(); // boolean canRename(); // private boolean canRenamePrototypeProperty(); // private boolean canRenameObjLitProperty(); // @Override // public void visit(NodeTraversal t, Node n, Node parent); // @Override // public void visit(NodeTraversal t, Node n, Node parent); // private void processPrototypeParent(Node n, CompilerInput input); // private void markPrototypePropertyCandidate(Node n, CompilerInput input); // private void markObjLitPropertyCandidate(Node n, CompilerInput input); // private void markPropertyAccessCandidate(Node n, CompilerInput input); // private Property getProperty(String name); // @Override // public int compare(Property a1, Property a2); // } // // // Abstract Java Test Class // package com.google.javascript.jscomp; // // // // public class RenamePrototypesTest extends CompilerTestCase { // private static final String EXTERNS = "var js_version;js_version.toString;"; // private VariableMap prevUsedRenameMap; // private RenamePrototypes renamePrototypes; // // public RenamePrototypesTest(); // @Override // public CompilerPass getProcessor(Compiler compiler); // @Override // protected void tearDown() throws Exception; // @Override // protected int getNumRepetitions(); // public void testRenamePrototypes1(); // public void testRenamePrototypes2(); // public void testRenamePrototypesWithGetOrSet(); // public void testRenameProperties(); // public void testBoth(); // public void testPropertyNameThatIsBothObjLitKeyAndPrototypeProperty(); // public void testModule(); // public void testStableSimple1(); // public void testStableSimple2(); // public void testStableSimple3(); // public void testStableOverlap(); // public void testStableTrickyExternedMethods(); // public void testStable(String input1, String expected1, // String input2, String expected2); // } // You are a professional Java test case writer, please create a test case named `testRenameProperties` for the `RenamePrototypes` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test renaming private properties (end with underscores) and test to make * sure we don't rename other properties. */
test/com/google/javascript/jscomp/RenamePrototypesTest.java
package com.google.javascript.jscomp; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage; import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.TokenStream; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.annotation.Nullable;
RenamePrototypes(AbstractCompiler compiler, boolean aggressiveRenaming, @Nullable char[] reservedCharacters, @Nullable VariableMap prevUsedRenameMap); @Override public void process(Node externs, Node root); private void reusePrototypeNames(Set<Property> properties); VariableMap getPropertyMap(); Property(String name); int count(); boolean canRename(); private boolean canRenamePrototypeProperty(); private boolean canRenameObjLitProperty(); @Override public void visit(NodeTraversal t, Node n, Node parent); @Override public void visit(NodeTraversal t, Node n, Node parent); private void processPrototypeParent(Node n, CompilerInput input); private void markPrototypePropertyCandidate(Node n, CompilerInput input); private void markObjLitPropertyCandidate(Node n, CompilerInput input); private void markPropertyAccessCandidate(Node n, CompilerInput input); private Property getProperty(String name); @Override public int compare(Property a1, Property a2);
141
testRenameProperties
```java // Abstract Java Tested Class package com.google.javascript.jscomp; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage; import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.TokenStream; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.annotation.Nullable; class RenamePrototypes implements CompilerPass { private final AbstractCompiler compiler; private final boolean aggressiveRenaming; private final char[] reservedCharacters; private final VariableMap prevUsedRenameMap; private static final Comparator<Property> FREQUENCY_COMPARATOR = new Comparator<Property>() { @Override public int compare(Property a1, Property a2) { int n1 = a1.count(); int n2 = a2.count(); if (n1 != n2) { return n2 - n1; } return a1.oldName.compareTo(a2.oldName); } }; private final Set<Node> stringNodes = new HashSet<Node>(); private final Map<String, Property> properties = new HashMap<String, Property>(); private final Set<String> reservedNames = new HashSet<String>(Arrays.asList( "indexOf", "lastIndexOf", "toString", "valueOf")); private final Set<Node> prototypeObjLits = new HashSet<Node>(); RenamePrototypes(AbstractCompiler compiler, boolean aggressiveRenaming, @Nullable char[] reservedCharacters, @Nullable VariableMap prevUsedRenameMap); @Override public void process(Node externs, Node root); private void reusePrototypeNames(Set<Property> properties); VariableMap getPropertyMap(); Property(String name); int count(); boolean canRename(); private boolean canRenamePrototypeProperty(); private boolean canRenameObjLitProperty(); @Override public void visit(NodeTraversal t, Node n, Node parent); @Override public void visit(NodeTraversal t, Node n, Node parent); private void processPrototypeParent(Node n, CompilerInput input); private void markPrototypePropertyCandidate(Node n, CompilerInput input); private void markObjLitPropertyCandidate(Node n, CompilerInput input); private void markPropertyAccessCandidate(Node n, CompilerInput input); private Property getProperty(String name); @Override public int compare(Property a1, Property a2); } // Abstract Java Test Class package com.google.javascript.jscomp; public class RenamePrototypesTest extends CompilerTestCase { private static final String EXTERNS = "var js_version;js_version.toString;"; private VariableMap prevUsedRenameMap; private RenamePrototypes renamePrototypes; public RenamePrototypesTest(); @Override public CompilerPass getProcessor(Compiler compiler); @Override protected void tearDown() throws Exception; @Override protected int getNumRepetitions(); public void testRenamePrototypes1(); public void testRenamePrototypes2(); public void testRenamePrototypesWithGetOrSet(); public void testRenameProperties(); public void testBoth(); public void testPropertyNameThatIsBothObjLitKeyAndPrototypeProperty(); public void testModule(); public void testStableSimple1(); public void testStableSimple2(); public void testStableSimple3(); public void testStableOverlap(); public void testStableTrickyExternedMethods(); public void testStable(String input1, String expected1, String input2, String expected2); } ``` You are a professional Java test case writer, please create a test case named `testRenameProperties` for the `RenamePrototypes` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test renaming private properties (end with underscores) and test to make * sure we don't rename other properties. */
133
// // Abstract Java Tested Class // package com.google.javascript.jscomp; // // import com.google.common.base.Preconditions; // import com.google.common.collect.ImmutableMap; // import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage; // import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback; // import com.google.javascript.rhino.Node; // import com.google.javascript.rhino.Token; // import com.google.javascript.rhino.TokenStream; // import java.util.Arrays; // import java.util.Comparator; // import java.util.HashMap; // import java.util.HashSet; // import java.util.Iterator; // import java.util.Map; // import java.util.Set; // import java.util.SortedSet; // import java.util.TreeSet; // import javax.annotation.Nullable; // // // // class RenamePrototypes implements CompilerPass { // private final AbstractCompiler compiler; // private final boolean aggressiveRenaming; // private final char[] reservedCharacters; // private final VariableMap prevUsedRenameMap; // private static final Comparator<Property> FREQUENCY_COMPARATOR = // new Comparator<Property>() { // @Override // public int compare(Property a1, Property a2) { // int n1 = a1.count(); // int n2 = a2.count(); // if (n1 != n2) { // return n2 - n1; // } // return a1.oldName.compareTo(a2.oldName); // } // }; // private final Set<Node> stringNodes = new HashSet<Node>(); // private final Map<String, Property> properties = // new HashMap<String, Property>(); // private final Set<String> reservedNames = // new HashSet<String>(Arrays.asList( // "indexOf", "lastIndexOf", "toString", "valueOf")); // private final Set<Node> prototypeObjLits = new HashSet<Node>(); // // RenamePrototypes(AbstractCompiler compiler, boolean aggressiveRenaming, // @Nullable char[] reservedCharacters, // @Nullable VariableMap prevUsedRenameMap); // @Override // public void process(Node externs, Node root); // private void reusePrototypeNames(Set<Property> properties); // VariableMap getPropertyMap(); // Property(String name); // int count(); // boolean canRename(); // private boolean canRenamePrototypeProperty(); // private boolean canRenameObjLitProperty(); // @Override // public void visit(NodeTraversal t, Node n, Node parent); // @Override // public void visit(NodeTraversal t, Node n, Node parent); // private void processPrototypeParent(Node n, CompilerInput input); // private void markPrototypePropertyCandidate(Node n, CompilerInput input); // private void markObjLitPropertyCandidate(Node n, CompilerInput input); // private void markPropertyAccessCandidate(Node n, CompilerInput input); // private Property getProperty(String name); // @Override // public int compare(Property a1, Property a2); // } // // // Abstract Java Test Class // package com.google.javascript.jscomp; // // // // public class RenamePrototypesTest extends CompilerTestCase { // private static final String EXTERNS = "var js_version;js_version.toString;"; // private VariableMap prevUsedRenameMap; // private RenamePrototypes renamePrototypes; // // public RenamePrototypesTest(); // @Override // public CompilerPass getProcessor(Compiler compiler); // @Override // protected void tearDown() throws Exception; // @Override // protected int getNumRepetitions(); // public void testRenamePrototypes1(); // public void testRenamePrototypes2(); // public void testRenamePrototypesWithGetOrSet(); // public void testRenameProperties(); // public void testBoth(); // public void testPropertyNameThatIsBothObjLitKeyAndPrototypeProperty(); // public void testModule(); // public void testStableSimple1(); // public void testStableSimple2(); // public void testStableSimple3(); // public void testStableOverlap(); // public void testStableTrickyExternedMethods(); // public void testStable(String input1, String expected1, // String input2, String expected2); // } // You are a professional Java test case writer, please create a test case named `testRenameProperties` for the `RenamePrototypes` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test renaming private properties (end with underscores) and test to make * sure we don't rename other properties. */ public void testRenameProperties() {
/** * Test renaming private properties (end with underscores) and test to make * sure we don't rename other properties. */
107
com.google.javascript.jscomp.RenamePrototypes
test
```java // Abstract Java Tested Class package com.google.javascript.jscomp; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage; import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.TokenStream; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.annotation.Nullable; class RenamePrototypes implements CompilerPass { private final AbstractCompiler compiler; private final boolean aggressiveRenaming; private final char[] reservedCharacters; private final VariableMap prevUsedRenameMap; private static final Comparator<Property> FREQUENCY_COMPARATOR = new Comparator<Property>() { @Override public int compare(Property a1, Property a2) { int n1 = a1.count(); int n2 = a2.count(); if (n1 != n2) { return n2 - n1; } return a1.oldName.compareTo(a2.oldName); } }; private final Set<Node> stringNodes = new HashSet<Node>(); private final Map<String, Property> properties = new HashMap<String, Property>(); private final Set<String> reservedNames = new HashSet<String>(Arrays.asList( "indexOf", "lastIndexOf", "toString", "valueOf")); private final Set<Node> prototypeObjLits = new HashSet<Node>(); RenamePrototypes(AbstractCompiler compiler, boolean aggressiveRenaming, @Nullable char[] reservedCharacters, @Nullable VariableMap prevUsedRenameMap); @Override public void process(Node externs, Node root); private void reusePrototypeNames(Set<Property> properties); VariableMap getPropertyMap(); Property(String name); int count(); boolean canRename(); private boolean canRenamePrototypeProperty(); private boolean canRenameObjLitProperty(); @Override public void visit(NodeTraversal t, Node n, Node parent); @Override public void visit(NodeTraversal t, Node n, Node parent); private void processPrototypeParent(Node n, CompilerInput input); private void markPrototypePropertyCandidate(Node n, CompilerInput input); private void markObjLitPropertyCandidate(Node n, CompilerInput input); private void markPropertyAccessCandidate(Node n, CompilerInput input); private Property getProperty(String name); @Override public int compare(Property a1, Property a2); } // Abstract Java Test Class package com.google.javascript.jscomp; public class RenamePrototypesTest extends CompilerTestCase { private static final String EXTERNS = "var js_version;js_version.toString;"; private VariableMap prevUsedRenameMap; private RenamePrototypes renamePrototypes; public RenamePrototypesTest(); @Override public CompilerPass getProcessor(Compiler compiler); @Override protected void tearDown() throws Exception; @Override protected int getNumRepetitions(); public void testRenamePrototypes1(); public void testRenamePrototypes2(); public void testRenamePrototypesWithGetOrSet(); public void testRenameProperties(); public void testBoth(); public void testPropertyNameThatIsBothObjLitKeyAndPrototypeProperty(); public void testModule(); public void testStableSimple1(); public void testStableSimple2(); public void testStableSimple3(); public void testStableOverlap(); public void testStableTrickyExternedMethods(); public void testStable(String input1, String expected1, String input2, String expected2); } ``` You are a professional Java test case writer, please create a test case named `testRenameProperties` for the `RenamePrototypes` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test renaming private properties (end with underscores) and test to make * sure we don't rename other properties. */ public void testRenameProperties() { ```
class RenamePrototypes implements CompilerPass
package com.google.javascript.jscomp;
public RenamePrototypesTest(); @Override public CompilerPass getProcessor(Compiler compiler); @Override protected void tearDown() throws Exception; @Override protected int getNumRepetitions(); public void testRenamePrototypes1(); public void testRenamePrototypes2(); public void testRenamePrototypesWithGetOrSet(); public void testRenameProperties(); public void testBoth(); public void testPropertyNameThatIsBothObjLitKeyAndPrototypeProperty(); public void testModule(); public void testStableSimple1(); public void testStableSimple2(); public void testStableSimple3(); public void testStableOverlap(); public void testStableTrickyExternedMethods(); public void testStable(String input1, String expected1, String input2, String expected2);
65bb26f25cee97b106d37eca14e9ba50f9c83b7b933102e6cf1f3baa189019b1
[ "com.google.javascript.jscomp.RenamePrototypesTest::testRenameProperties" ]
private final AbstractCompiler compiler; private final boolean aggressiveRenaming; private final char[] reservedCharacters; private final VariableMap prevUsedRenameMap; private static final Comparator<Property> FREQUENCY_COMPARATOR = new Comparator<Property>() { @Override public int compare(Property a1, Property a2) { int n1 = a1.count(); int n2 = a2.count(); if (n1 != n2) { return n2 - n1; } return a1.oldName.compareTo(a2.oldName); } }; private final Set<Node> stringNodes = new HashSet<Node>(); private final Map<String, Property> properties = new HashMap<String, Property>(); private final Set<String> reservedNames = new HashSet<String>(Arrays.asList( "indexOf", "lastIndexOf", "toString", "valueOf")); private final Set<Node> prototypeObjLits = new HashSet<Node>();
public void testRenameProperties()
private static final String EXTERNS = "var js_version;js_version.toString;"; private VariableMap prevUsedRenameMap; private RenamePrototypes renamePrototypes;
Closure
/* * Copyright 2005 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; public class RenamePrototypesTest extends CompilerTestCase { private static final String EXTERNS = "var js_version;js_version.toString;"; private VariableMap prevUsedRenameMap; private RenamePrototypes renamePrototypes; public RenamePrototypesTest() { super(EXTERNS); enableNormalize(); } @Override public CompilerPass getProcessor(Compiler compiler) { return renamePrototypes = new RenamePrototypes(compiler, true, null, prevUsedRenameMap); } @Override protected void tearDown() throws Exception { super.tearDown(); prevUsedRenameMap = null; } @Override protected int getNumRepetitions() { // The RenamePrototypes pass should only be run once over a parse tree. return 1; } public void testRenamePrototypes1() { test("Bar.prototype={'getFoo':function(){},2:function(){}}", "Bar.prototype={'a':function(){},2:function(){}}"); } public void testRenamePrototypes2() { // Simple test("Bar.prototype.getFoo=function(){};Bar.getFoo(b);" + "Bar.prototype.getBaz=function(){}", "Bar.prototype.a=function(){};Bar.a(b);" + "Bar.prototype.b=function(){}"); test("Bar.prototype['getFoo']=function(){};Bar.getFoo(b);" + "Bar.prototype['getBaz']=function(){}", "Bar.prototype['a']=function(){};Bar.a(b);" + "Bar.prototype['b']=function(){}"); test("Bar.prototype={'getFoo':function(){},2:function(){}}", "Bar.prototype={'a':function(){},2:function(){}}"); test("Bar.prototype={'getFoo':function(){}," + "'getBar':function(){}};b.getFoo()", "Bar.prototype={'a':function(){}," + "'b':function(){}};b.a()"); test("Bar.prototype={'B':function(){}," + "'getBar':function(){}};b.getBar()", "Bar.prototype={'b':function(){}," + "'a':function(){}};b.a()"); // overlap test("Bar.prototype={'a':function(){}," + "'b':function(){}};b.b()", "Bar.prototype={'b':function(){}," + "'a':function(){}};b.a()"); // don't rename anything with a leading underscore test("Bar.prototype={'_getFoo':function(){}," + "'getBar':function(){}};b._getFoo()", "Bar.prototype={'_getFoo':function(){}," + "'a':function(){}};b._getFoo()"); // Externed methods test("Bar.prototype={'toString':function(){}," + "'getBar':function(){}};b.toString()", "Bar.prototype={'toString':function(){}," + "'a':function(){}};b.toString()"); // don't rename a method to an existing (unrenamed) property test("Bar.prototype.foo=function(){}" + ";bar.foo();bar.a", "Bar.prototype.b=function(){}" + ";bar.b();bar.a"); } public void testRenamePrototypesWithGetOrSet() { // Simple // TODO(johnlenz): Enable these for after Rhino support is added. // test("Bar.prototype={get 'getFoo'(){}}", // "Bar.prototype={get a(){}}"); // test("Bar.prototype={get 2(){}}", // "Bar.prototype={get 2(){}}"); test("Bar.prototype={get getFoo(){}}", "Bar.prototype={get a(){}}"); test("Bar.prototype={get getFoo(){}}; a.getFoo;", "Bar.prototype={get a(){}}; a.a;"); // TODO(johnlenz): Enable these for after Rhino support is added. // test("Bar.prototype={set 'getFoo'(x){}}", // "Bar.prototype={set a(x){}}"); // test("Bar.prototype={set 2(x){}}", // "Bar.prototype={set 2(x){}}"); test("Bar.prototype={set getFoo(x){}}", "Bar.prototype={set a(x){}}"); test("Bar.prototype={set getFoo(x){}}; a.getFoo;", "Bar.prototype={set a(x){}}; a.a;"); // overlap test("Bar.prototype={get a(){}," + "get b(){}};b.b()", "Bar.prototype={get b(){}," + "get a(){}};b.a()"); } /** * Test renaming private properties (end with underscores) and test to make * sure we don't rename other properties. */ public void testRenameProperties() { test("var foo; foo.prop_='bar'", "var foo;foo.a='bar'"); test("this.prop_='bar'", "this.a='bar'"); test("this.prop='bar'", "this.prop='bar'"); test("this['prop_']='bar'", "this['a']='bar'"); test("this['prop']='bar'", "this['prop']='bar'"); test("var foo={prop1_: 'bar',prop2_: 'baz'};", "var foo={a:'bar',b:'baz'}"); } /** * Tests a potential tricky interaction between prototype renaming and * property renaming. */ public void testBoth() { test("Bar.prototype.getFoo_=function(){};Bar.getFoo_(b);" + "Bar.prototype.getBaz_=function(){}", "Bar.prototype.a=function(){};Bar.a(b);" + "Bar.prototype.b=function(){}"); } public void testPropertyNameThatIsBothObjLitKeyAndPrototypeProperty() { // This test protects against regression of a bug where non-private object // literal keys were getting renamed if they clashed with custom prototype // methods. Now we don't simply don't rename in this situation, since // references like z.myprop are ambiguous. test("x.prototype.myprop=function(){};y={myprop:0};z.myprop", "x.prototype.myprop=function(){};y={myprop:0};z.myprop"); // This test shows that a property can be renamed if both the prototype // property renaming policy and the objlit key renaming policy agree that // it can be renamed. test("x.prototype.myprop_=function(){};y={myprop_:0};z.myprop_", "x.prototype.a=function(){};y={a:0};z.a"); } public void testModule() { JSModule[] modules = createModules( "function Bar(){} var foo; Bar.prototype.getFoo_=function(x){};" + "foo.getFoo_(foo);foo.doo_=foo;foo.bloo_=foo;", "function Far(){} var too; Far.prototype.getGoo_=function(x){};" + "too.getGoo_(too);too.troo_=too;too.bloo_=too;"); test(modules, new String[] { "function Bar(){}var foo; Bar.prototype.a=function(x){};" + "foo.a(foo);foo.d=foo;foo.c=foo;", "function Far(){}var too; Far.prototype.b=function(x){};" + "too.b(too);too.e=too;too.c=too;" }); } public void testStableSimple1() { testStable( "Bar.prototype.getFoo=function(){};Bar.getFoo(b);" + "Bar.prototype.getBaz=function(){}", "Bar.prototype.a=function(){};Bar.a(b);" + "Bar.prototype.b=function(){}", "Bar.prototype.getBar=function(){};Bar.getBar(b);" + "Bar.prototype.getFoo=function(){};Bar.getFoo(b);" + "Bar.prototype.getBaz=function(){}", "Bar.prototype.c=function(){};Bar.c(b);" + "Bar.prototype.a=function(){};Bar.a(b);" + "Bar.prototype.b=function(){}"); } public void testStableSimple2() { testStable( "Bar.prototype['getFoo']=function(){};Bar.getFoo(b);" + "Bar.prototype['getBaz']=function(){}", "Bar.prototype['a']=function(){};Bar.a(b);" + "Bar.prototype['b']=function(){}", "Bar.prototype['getFoo']=function(){};Bar.getFoo(b);" + "Bar.prototype['getBar']=function(){};" + "Bar.prototype['getBaz']=function(){}", "Bar.prototype['a']=function(){};Bar.a(b);" + "Bar.prototype['c']=function(){};" + "Bar.prototype['b']=function(){}"); } public void testStableSimple3() { testStable( "Bar.prototype={'getFoo':function(){}," + "'getBar':function(){}};b.getFoo()", "Bar.prototype={'a':function(){}, 'b':function(){}};b.a()", "Bar.prototype={'getFoo':function(){}," + "'getBaz':function(){},'getBar':function(){}};b.getFoo()", "Bar.prototype={'a':function(){}, " + "'c':function(){}, 'b':function(){}};b.a()"); } public void testStableOverlap() { testStable( "Bar.prototype={'a':function(){},'b':function(){}};b.b()", "Bar.prototype={'b':function(){},'a':function(){}};b.a()", "Bar.prototype={'a':function(){},'b':function(){}};b.b()", "Bar.prototype={'b':function(){},'a':function(){}};b.a()"); } public void testStableTrickyExternedMethods() { test("Bar.prototype={'toString':function(){}," + "'getBar':function(){}};b.toString()", "Bar.prototype={'toString':function(){}," + "'a':function(){}};b.toString()"); prevUsedRenameMap = renamePrototypes.getPropertyMap(); String externs = EXTERNS + "prop.a;"; test(externs, "Bar.prototype={'toString':function(){}," + "'getBar':function(){}};b.toString()", "Bar.prototype={'toString':function(){}," + "'b':function(){}};b.toString()", null, null); } public void testStable(String input1, String expected1, String input2, String expected2) { test(input1, expected1); prevUsedRenameMap = renamePrototypes.getPropertyMap(); test(input2, expected2); } }
[ { "be_test_class_file": "com/google/javascript/jscomp/RenamePrototypes.java", "be_test_class_name": "com.google.javascript.jscomp.RenamePrototypes", "be_test_function_name": "access$700", "be_test_function_signature": "(Lcom/google/javascript/jscomp/RenamePrototypes;)Ljava/util/Map;", "line_numbers": [ "60" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/RenamePrototypes.java", "be_test_class_name": "com.google.javascript.jscomp.RenamePrototypes", "be_test_function_name": "process", "be_test_function_signature": "(Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "207", "209", "211", "214", "217", "218", "219", "220", "221", "223", "227", "229", "232", "233", "237", "239", "240", "241", "242", "243", "246", "247", "249", "252", "253", "254", "255", "256", "257", "258", "260", "262", "263", "266", "267" ], "method_line_rate": 0.9714285714285714 } ]
public class ErfTest
@Test public void testErfGnu() { final double tol = 1E-15; final double[] gnuValues = new double[] {-1, -1, -1, -1, -1, -1, -1, -1, -0.99999999999999997848, -0.99999999999999264217, -0.99999999999846254017, -0.99999999980338395581, -0.99999998458274209971, -0.9999992569016276586, -0.99997790950300141459, -0.99959304798255504108, -0.99532226501895273415, -0.96610514647531072711, -0.84270079294971486948, -0.52049987781304653809, 0, 0.52049987781304653809, 0.84270079294971486948, 0.96610514647531072711, 0.99532226501895273415, 0.99959304798255504108, 0.99997790950300141459, 0.9999992569016276586, 0.99999998458274209971, 0.99999999980338395581, 0.99999999999846254017, 0.99999999999999264217, 0.99999999999999997848, 1, 1, 1, 1, 1, 1, 1, 1}; double x = -10d; for (int i = 0; i < 41; i++) { Assert.assertEquals(gnuValues[i], Erf.erf(x), tol); x += 0.5d; } }
// // Abstract Java Tested Class // package org.apache.commons.math3.special; // // import org.apache.commons.math3.util.FastMath; // // // // public class Erf { // private static final double X_CRIT = 0.4769362762044697; // // private Erf(); // public static double erf(double x); // public static double erfc(double x); // public static double erf(double x1, double x2); // public static double erfInv(final double x); // public static double erfcInv(final double x); // } // // // Abstract Java Test Class // package org.apache.commons.math3.special; // // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.util.FastMath; // import org.junit.Test; // import org.junit.Assert; // // // // public class ErfTest { // // // @Test // public void testErf0(); // @Test // public void testErf1960(); // @Test // public void testErf2576(); // @Test // public void testErf2807(); // @Test // public void testErf3291(); // @Test // public void testLargeValues(); // @Test // public void testErfGnu(); // @Test // public void testErfcGnu(); // @Test // public void testErfcMaple(); // @Test // public void testTwoArgumentErf(); // @Test // public void testErfInvNaN(); // @Test // public void testErfInvInfinite(); // @Test // public void testErfInv(); // @Test // public void testErfcInvNaN(); // @Test // public void testErfcInvInfinite(); // @Test // public void testErfcInv(); // } // You are a professional Java test case writer, please create a test case named `testErfGnu` for the `Erf` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Compare Erf.erf against reference values computed using GCC 4.2.1 (Apple OSX packaged version) * erfl (extended precision erf). */
src/test/java/org/apache/commons/math3/special/ErfTest.java
package org.apache.commons.math3.special; import org.apache.commons.math3.util.FastMath;
private Erf(); public static double erf(double x); public static double erfc(double x); public static double erf(double x1, double x2); public static double erfInv(final double x); public static double erfcInv(final double x);
140
testErfGnu
```java // Abstract Java Tested Class package org.apache.commons.math3.special; import org.apache.commons.math3.util.FastMath; public class Erf { private static final double X_CRIT = 0.4769362762044697; private Erf(); public static double erf(double x); public static double erfc(double x); public static double erf(double x1, double x2); public static double erfInv(final double x); public static double erfcInv(final double x); } // Abstract Java Test Class package org.apache.commons.math3.special; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert; public class ErfTest { @Test public void testErf0(); @Test public void testErf1960(); @Test public void testErf2576(); @Test public void testErf2807(); @Test public void testErf3291(); @Test public void testLargeValues(); @Test public void testErfGnu(); @Test public void testErfcGnu(); @Test public void testErfcMaple(); @Test public void testTwoArgumentErf(); @Test public void testErfInvNaN(); @Test public void testErfInvInfinite(); @Test public void testErfInv(); @Test public void testErfcInvNaN(); @Test public void testErfcInvInfinite(); @Test public void testErfcInv(); } ``` You are a professional Java test case writer, please create a test case named `testErfGnu` for the `Erf` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Compare Erf.erf against reference values computed using GCC 4.2.1 (Apple OSX packaged version) * erfl (extended precision erf). */
122
// // Abstract Java Tested Class // package org.apache.commons.math3.special; // // import org.apache.commons.math3.util.FastMath; // // // // public class Erf { // private static final double X_CRIT = 0.4769362762044697; // // private Erf(); // public static double erf(double x); // public static double erfc(double x); // public static double erf(double x1, double x2); // public static double erfInv(final double x); // public static double erfcInv(final double x); // } // // // Abstract Java Test Class // package org.apache.commons.math3.special; // // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.util.FastMath; // import org.junit.Test; // import org.junit.Assert; // // // // public class ErfTest { // // // @Test // public void testErf0(); // @Test // public void testErf1960(); // @Test // public void testErf2576(); // @Test // public void testErf2807(); // @Test // public void testErf3291(); // @Test // public void testLargeValues(); // @Test // public void testErfGnu(); // @Test // public void testErfcGnu(); // @Test // public void testErfcMaple(); // @Test // public void testTwoArgumentErf(); // @Test // public void testErfInvNaN(); // @Test // public void testErfInvInfinite(); // @Test // public void testErfInv(); // @Test // public void testErfcInvNaN(); // @Test // public void testErfcInvInfinite(); // @Test // public void testErfcInv(); // } // You are a professional Java test case writer, please create a test case named `testErfGnu` for the `Erf` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Compare Erf.erf against reference values computed using GCC 4.2.1 (Apple OSX packaged version) * erfl (extended precision erf). */ @Test public void testErfGnu() {
/** * Compare Erf.erf against reference values computed using GCC 4.2.1 (Apple OSX packaged version) * erfl (extended precision erf). */
1
org.apache.commons.math3.special.Erf
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.math3.special; import org.apache.commons.math3.util.FastMath; public class Erf { private static final double X_CRIT = 0.4769362762044697; private Erf(); public static double erf(double x); public static double erfc(double x); public static double erf(double x1, double x2); public static double erfInv(final double x); public static double erfcInv(final double x); } // Abstract Java Test Class package org.apache.commons.math3.special; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert; public class ErfTest { @Test public void testErf0(); @Test public void testErf1960(); @Test public void testErf2576(); @Test public void testErf2807(); @Test public void testErf3291(); @Test public void testLargeValues(); @Test public void testErfGnu(); @Test public void testErfcGnu(); @Test public void testErfcMaple(); @Test public void testTwoArgumentErf(); @Test public void testErfInvNaN(); @Test public void testErfInvInfinite(); @Test public void testErfInv(); @Test public void testErfcInvNaN(); @Test public void testErfcInvInfinite(); @Test public void testErfcInv(); } ``` You are a professional Java test case writer, please create a test case named `testErfGnu` for the `Erf` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Compare Erf.erf against reference values computed using GCC 4.2.1 (Apple OSX packaged version) * erfl (extended precision erf). */ @Test public void testErfGnu() { ```
public class Erf
package org.apache.commons.math3.special; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert;
@Test public void testErf0(); @Test public void testErf1960(); @Test public void testErf2576(); @Test public void testErf2807(); @Test public void testErf3291(); @Test public void testLargeValues(); @Test public void testErfGnu(); @Test public void testErfcGnu(); @Test public void testErfcMaple(); @Test public void testTwoArgumentErf(); @Test public void testErfInvNaN(); @Test public void testErfInvInfinite(); @Test public void testErfInv(); @Test public void testErfcInvNaN(); @Test public void testErfcInvInfinite(); @Test public void testErfcInv();
660f4f065ef44e98248b7eb98dccb4013472244ce14223c54e09122b5e08f7e5
[ "org.apache.commons.math3.special.ErfTest::testErfGnu" ]
private static final double X_CRIT = 0.4769362762044697;
@Test public void testErfGnu()
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.special; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Test; import org.junit.Assert; /** * @version $Id$ */ public class ErfTest { @Test public void testErf0() { double actual = Erf.erf(0.0); double expected = 0.0; Assert.assertEquals(expected, actual, 1.0e-15); Assert.assertEquals(1 - expected, Erf.erfc(0.0), 1.0e-15); } @Test public void testErf1960() { double x = 1.960 / FastMath.sqrt(2.0); double actual = Erf.erf(x); double expected = 0.95; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(x), 1.0e-15); actual = Erf.erf(-x); expected = -expected; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(-x), 1.0e-15); } @Test public void testErf2576() { double x = 2.576 / FastMath.sqrt(2.0); double actual = Erf.erf(x); double expected = 0.99; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(x), 1e-15); actual = Erf.erf(-x); expected = -expected; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(-x), 1.0e-15); } @Test public void testErf2807() { double x = 2.807 / FastMath.sqrt(2.0); double actual = Erf.erf(x); double expected = 0.995; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(x), 1.0e-15); actual = Erf.erf(-x); expected = -expected; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - actual, Erf.erfc(-x), 1.0e-15); } @Test public void testErf3291() { double x = 3.291 / FastMath.sqrt(2.0); double actual = Erf.erf(x); double expected = 0.999; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - expected, Erf.erfc(x), 1.0e-5); actual = Erf.erf(-x); expected = -expected; Assert.assertEquals(expected, actual, 1.0e-5); Assert.assertEquals(1 - expected, Erf.erfc(-x), 1.0e-5); } /** * MATH-301, MATH-456 */ @Test public void testLargeValues() { for (int i = 1; i < 200; i*=10) { double result = Erf.erf(i); Assert.assertFalse(Double.isNaN(result)); Assert.assertTrue(result > 0 && result <= 1); result = Erf.erf(-i); Assert.assertFalse(Double.isNaN(result)); Assert.assertTrue(result >= -1 && result < 0); result = Erf.erfc(i); Assert.assertFalse(Double.isNaN(result)); Assert.assertTrue(result >= 0 && result < 1); result = Erf.erfc(-i); Assert.assertFalse(Double.isNaN(result)); Assert.assertTrue(result >= 1 && result <= 2); } Assert.assertEquals(-1, Erf.erf(Double.NEGATIVE_INFINITY), 0); Assert.assertEquals(1, Erf.erf(Double.POSITIVE_INFINITY), 0); Assert.assertEquals(2, Erf.erfc(Double.NEGATIVE_INFINITY), 0); Assert.assertEquals(0, Erf.erfc(Double.POSITIVE_INFINITY), 0); } /** * Compare Erf.erf against reference values computed using GCC 4.2.1 (Apple OSX packaged version) * erfl (extended precision erf). */ @Test public void testErfGnu() { final double tol = 1E-15; final double[] gnuValues = new double[] {-1, -1, -1, -1, -1, -1, -1, -1, -0.99999999999999997848, -0.99999999999999264217, -0.99999999999846254017, -0.99999999980338395581, -0.99999998458274209971, -0.9999992569016276586, -0.99997790950300141459, -0.99959304798255504108, -0.99532226501895273415, -0.96610514647531072711, -0.84270079294971486948, -0.52049987781304653809, 0, 0.52049987781304653809, 0.84270079294971486948, 0.96610514647531072711, 0.99532226501895273415, 0.99959304798255504108, 0.99997790950300141459, 0.9999992569016276586, 0.99999998458274209971, 0.99999999980338395581, 0.99999999999846254017, 0.99999999999999264217, 0.99999999999999997848, 1, 1, 1, 1, 1, 1, 1, 1}; double x = -10d; for (int i = 0; i < 41; i++) { Assert.assertEquals(gnuValues[i], Erf.erf(x), tol); x += 0.5d; } } /** * Compare Erf.erfc against reference values computed using GCC 4.2.1 (Apple OSX packaged version) * erfcl (extended precision erfc). */ @Test public void testErfcGnu() { final double tol = 1E-15; final double[] gnuValues = new double[] { 2, 2, 2, 2, 2, 2, 2, 2, 1.9999999999999999785, 1.9999999999999926422, 1.9999999999984625402, 1.9999999998033839558, 1.9999999845827420998, 1.9999992569016276586, 1.9999779095030014146, 1.9995930479825550411, 1.9953222650189527342, 1.9661051464753107271, 1.8427007929497148695, 1.5204998778130465381, 1, 0.47950012218695346194, 0.15729920705028513051, 0.033894853524689272893, 0.0046777349810472658333, 0.00040695201744495893941, 2.2090496998585441366E-05, 7.4309837234141274516E-07, 1.5417257900280018858E-08, 1.966160441542887477E-10, 1.5374597944280348501E-12, 7.3578479179743980661E-15, 2.1519736712498913103E-17, 3.8421483271206474691E-20, 4.1838256077794144006E-23, 2.7766493860305691016E-26, 1.1224297172982927079E-29, 2.7623240713337714448E-33, 4.1370317465138102353E-37, 3.7692144856548799402E-41, 2.0884875837625447567E-45}; double x = -10d; for (int i = 0; i < 41; i++) { Assert.assertEquals(gnuValues[i], Erf.erfc(x), tol); x += 0.5d; } } /** * Tests erfc against reference data computed using Maple reported in Marsaglia, G,, * "Evaluating the Normal Distribution," Journal of Statistical Software, July, 2004. * http//www.jstatsoft.org/v11/a05/paper */ @Test public void testErfcMaple() { double[][] ref = new double[][] {{0.1, 4.60172162722971e-01}, {1.2, 1.15069670221708e-01}, {2.3, 1.07241100216758e-02}, {3.4, 3.36929265676881e-04}, {4.5, 3.39767312473006e-06}, {5.6, 1.07175902583109e-08}, {6.7, 1.04209769879652e-11}, {7.8, 3.09535877195870e-15}, {8.9, 2.79233437493966e-19}, {10.0, 7.61985302416053e-24}, {11.1, 6.27219439321703e-29}, {12.2, 1.55411978638959e-34}, {13.3, 1.15734162836904e-40}, {14.4, 2.58717592540226e-47}, {15.5, 1.73446079179387e-54}, {16.6, 3.48454651995041e-62} }; for (int i = 0; i < 15; i++) { final double result = 0.5*Erf.erfc(ref[i][0]/Math.sqrt(2)); Assert.assertEquals(ref[i][1], result, 1E-15); TestUtils.assertRelativelyEquals(ref[i][1], result, 1E-13); } } /** * Test the implementation of Erf.erf(double, double) for consistency with results * obtained from Erf.erf(double) and Erf.erfc(double). */ @Test public void testTwoArgumentErf() { double[] xi = new double[]{-2.0, -1.0, -0.9, -0.1, 0.0, 0.1, 0.9, 1.0, 2.0}; for(double x1 : xi) { for(double x2 : xi) { double a = Erf.erf(x1, x2); double b = Erf.erf(x2) - Erf.erf(x1); double c = Erf.erfc(x1) - Erf.erfc(x2); Assert.assertEquals(a, b, 1E-15); Assert.assertEquals(a, c, 1E-15); } } } @Test public void testErfInvNaN() { Assert.assertTrue(Double.isNaN(Erf.erfInv(-1.001))); Assert.assertTrue(Double.isNaN(Erf.erfInv(+1.001))); } @Test public void testErfInvInfinite() { Assert.assertTrue(Double.isInfinite(Erf.erfInv(-1))); Assert.assertTrue(Erf.erfInv(-1) < 0); Assert.assertTrue(Double.isInfinite(Erf.erfInv(+1))); Assert.assertTrue(Erf.erfInv(+1) > 0); } @Test public void testErfInv() { for (double x = -5.9; x < 5.9; x += 0.01) { final double y = Erf.erf(x); final double dydx = 2 * FastMath.exp(-x * x) / FastMath.sqrt(FastMath.PI); Assert.assertEquals(x, Erf.erfInv(y), 1.0e-15 / dydx); } } @Test public void testErfcInvNaN() { Assert.assertTrue(Double.isNaN(Erf.erfcInv(-0.001))); Assert.assertTrue(Double.isNaN(Erf.erfcInv(+2.001))); } @Test public void testErfcInvInfinite() { Assert.assertTrue(Double.isInfinite(Erf.erfcInv(-0))); Assert.assertTrue(Erf.erfcInv( 0) > 0); Assert.assertTrue(Double.isInfinite(Erf.erfcInv(+2))); Assert.assertTrue(Erf.erfcInv(+2) < 0); } @Test public void testErfcInv() { for (double x = -5.85; x < 5.9; x += 0.01) { final double y = Erf.erfc(x); final double dydxAbs = 2 * FastMath.exp(-x * x) / FastMath.sqrt(FastMath.PI); Assert.assertEquals(x, Erf.erfcInv(y), 1.0e-15 / dydxAbs); } } }
[ { "be_test_class_file": "org/apache/commons/math3/special/Erf.java", "be_test_class_name": "org.apache.commons.math3.special.Erf", "be_test_function_name": "erf", "be_test_function_signature": "(D)D", "line_numbers": [ "67", "68", "70", "71" ], "method_line_rate": 0.75 } ]
public final class SmoothingPolynomialBicubicSplineInterpolatorTest
@Test public void testParaboloid() { BivariateFunction f = new BivariateFunction() { public double value(double x, double y) { return 2 * x * x - 3 * y * y + 4 * x * y - 5 + ((int) (FastMath.abs(5 * x + 3 * y)) % 2 == 0 ? 1 : -1); } }; BivariateGridInterpolator interpolator = new SmoothingPolynomialBicubicSplineInterpolator(4); double[] xval = new double[] {3, 4, 5, 6.5}; double[] yval = new double[] {-4, -3, -2, -1, 0.5, 2.5}; double[][] zval = new double[xval.length][yval.length]; for (int i = 0; i < xval.length; i++) { for (int j = 0; j < yval.length; j++) { zval[i][j] = f.value(xval[i], yval[j]); } } BivariateFunction p = interpolator.interpolate(xval, yval, zval); double x, y; double expected, result; x = 5; y = 0.5; expected = f.value(x, y); result = p.value(x, y); Assert.assertEquals("On sample point", expected, result, 2); x = 4.5; y = -1.5; expected = f.value(x, y); result = p.value(x, y); Assert.assertEquals("half-way between sample points (middle of the patch)", expected, result, 2); x = 3.5; y = -3.5; expected = f.value(x, y); result = p.value(x, y); Assert.assertEquals("half-way between sample points (border of the patch)", expected, result, 2); }
// // Abstract Java Tested Class // package org.apache.commons.math3.analysis.interpolation; // // import org.apache.commons.math3.exception.DimensionMismatchException; // import org.apache.commons.math3.exception.NoDataException; // import org.apache.commons.math3.exception.NonMonotonicSequenceException; // import org.apache.commons.math3.exception.NotPositiveException; // import org.apache.commons.math3.exception.NullArgumentException; // import org.apache.commons.math3.util.MathArrays; // import org.apache.commons.math3.util.Precision; // import org.apache.commons.math3.optim.nonlinear.vector.jacobian.GaussNewtonOptimizer; // import org.apache.commons.math3.fitting.PolynomialFitter; // import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; // import org.apache.commons.math3.optim.SimpleVectorValueChecker; // // // // public class SmoothingPolynomialBicubicSplineInterpolator // extends BicubicSplineInterpolator { // private final PolynomialFitter xFitter; // private final int xDegree; // private final PolynomialFitter yFitter; // private final int yDegree; // // public SmoothingPolynomialBicubicSplineInterpolator(); // public SmoothingPolynomialBicubicSplineInterpolator(int degree) // throws NotPositiveException; // public SmoothingPolynomialBicubicSplineInterpolator(int xDegree, int yDegree) // throws NotPositiveException; // @Override // public BicubicSplineInterpolatingFunction interpolate(final double[] xval, // final double[] yval, // final double[][] fval) // throws NoDataException, NullArgumentException, // DimensionMismatchException, NonMonotonicSequenceException; // } // // // Abstract Java Test Class // package org.apache.commons.math3.analysis.interpolation; // // import org.apache.commons.math3.exception.DimensionMismatchException; // import org.apache.commons.math3.exception.MathIllegalArgumentException; // import org.apache.commons.math3.util.FastMath; // import org.apache.commons.math3.analysis.BivariateFunction; // import org.junit.Assert; // import org.junit.Test; // // // // public final class SmoothingPolynomialBicubicSplineInterpolatorTest { // // // @Test // public void testPreconditions(); // @Test // public void testPlane(); // @Test // public void testParaboloid(); // public double value(double x, double y); // public double value(double x, double y); // } // You are a professional Java test case writer, please create a test case named `testParaboloid` for the `SmoothingPolynomialBicubicSplineInterpolator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test of interpolator for a paraboloid. * <p> * z = 2 x<sup>2</sup> - 3 y<sup>2</sup> + 4 x y - 5 */
src/test/java/org/apache/commons/math3/analysis/interpolation/SmoothingPolynomialBicubicSplineInterpolatorTest.java
package org.apache.commons.math3.analysis.interpolation; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.NoDataException; import org.apache.commons.math3.exception.NonMonotonicSequenceException; import org.apache.commons.math3.exception.NotPositiveException; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.util.MathArrays; import org.apache.commons.math3.util.Precision; import org.apache.commons.math3.optim.nonlinear.vector.jacobian.GaussNewtonOptimizer; import org.apache.commons.math3.fitting.PolynomialFitter; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; import org.apache.commons.math3.optim.SimpleVectorValueChecker;
public SmoothingPolynomialBicubicSplineInterpolator(); public SmoothingPolynomialBicubicSplineInterpolator(int degree) throws NotPositiveException; public SmoothingPolynomialBicubicSplineInterpolator(int xDegree, int yDegree) throws NotPositiveException; @Override public BicubicSplineInterpolatingFunction interpolate(final double[] xval, final double[] yval, final double[][] fval) throws NoDataException, NullArgumentException, DimensionMismatchException, NonMonotonicSequenceException;
178
testParaboloid
```java // Abstract Java Tested Class package org.apache.commons.math3.analysis.interpolation; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.NoDataException; import org.apache.commons.math3.exception.NonMonotonicSequenceException; import org.apache.commons.math3.exception.NotPositiveException; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.util.MathArrays; import org.apache.commons.math3.util.Precision; import org.apache.commons.math3.optim.nonlinear.vector.jacobian.GaussNewtonOptimizer; import org.apache.commons.math3.fitting.PolynomialFitter; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; import org.apache.commons.math3.optim.SimpleVectorValueChecker; public class SmoothingPolynomialBicubicSplineInterpolator extends BicubicSplineInterpolator { private final PolynomialFitter xFitter; private final int xDegree; private final PolynomialFitter yFitter; private final int yDegree; public SmoothingPolynomialBicubicSplineInterpolator(); public SmoothingPolynomialBicubicSplineInterpolator(int degree) throws NotPositiveException; public SmoothingPolynomialBicubicSplineInterpolator(int xDegree, int yDegree) throws NotPositiveException; @Override public BicubicSplineInterpolatingFunction interpolate(final double[] xval, final double[] yval, final double[][] fval) throws NoDataException, NullArgumentException, DimensionMismatchException, NonMonotonicSequenceException; } // Abstract Java Test Class package org.apache.commons.math3.analysis.interpolation; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.analysis.BivariateFunction; import org.junit.Assert; import org.junit.Test; public final class SmoothingPolynomialBicubicSplineInterpolatorTest { @Test public void testPreconditions(); @Test public void testPlane(); @Test public void testParaboloid(); public double value(double x, double y); public double value(double x, double y); } ``` You are a professional Java test case writer, please create a test case named `testParaboloid` for the `SmoothingPolynomialBicubicSplineInterpolator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test of interpolator for a paraboloid. * <p> * z = 2 x<sup>2</sup> - 3 y<sup>2</sup> + 4 x y - 5 */
137
// // Abstract Java Tested Class // package org.apache.commons.math3.analysis.interpolation; // // import org.apache.commons.math3.exception.DimensionMismatchException; // import org.apache.commons.math3.exception.NoDataException; // import org.apache.commons.math3.exception.NonMonotonicSequenceException; // import org.apache.commons.math3.exception.NotPositiveException; // import org.apache.commons.math3.exception.NullArgumentException; // import org.apache.commons.math3.util.MathArrays; // import org.apache.commons.math3.util.Precision; // import org.apache.commons.math3.optim.nonlinear.vector.jacobian.GaussNewtonOptimizer; // import org.apache.commons.math3.fitting.PolynomialFitter; // import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; // import org.apache.commons.math3.optim.SimpleVectorValueChecker; // // // // public class SmoothingPolynomialBicubicSplineInterpolator // extends BicubicSplineInterpolator { // private final PolynomialFitter xFitter; // private final int xDegree; // private final PolynomialFitter yFitter; // private final int yDegree; // // public SmoothingPolynomialBicubicSplineInterpolator(); // public SmoothingPolynomialBicubicSplineInterpolator(int degree) // throws NotPositiveException; // public SmoothingPolynomialBicubicSplineInterpolator(int xDegree, int yDegree) // throws NotPositiveException; // @Override // public BicubicSplineInterpolatingFunction interpolate(final double[] xval, // final double[] yval, // final double[][] fval) // throws NoDataException, NullArgumentException, // DimensionMismatchException, NonMonotonicSequenceException; // } // // // Abstract Java Test Class // package org.apache.commons.math3.analysis.interpolation; // // import org.apache.commons.math3.exception.DimensionMismatchException; // import org.apache.commons.math3.exception.MathIllegalArgumentException; // import org.apache.commons.math3.util.FastMath; // import org.apache.commons.math3.analysis.BivariateFunction; // import org.junit.Assert; // import org.junit.Test; // // // // public final class SmoothingPolynomialBicubicSplineInterpolatorTest { // // // @Test // public void testPreconditions(); // @Test // public void testPlane(); // @Test // public void testParaboloid(); // public double value(double x, double y); // public double value(double x, double y); // } // You are a professional Java test case writer, please create a test case named `testParaboloid` for the `SmoothingPolynomialBicubicSplineInterpolator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test of interpolator for a paraboloid. * <p> * z = 2 x<sup>2</sup> - 3 y<sup>2</sup> + 4 x y - 5 */ @Test public void testParaboloid() {
/** * Test of interpolator for a paraboloid. * <p> * z = 2 x<sup>2</sup> - 3 y<sup>2</sup> + 4 x y - 5 */
1
org.apache.commons.math3.analysis.interpolation.SmoothingPolynomialBicubicSplineInterpolator
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.math3.analysis.interpolation; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.NoDataException; import org.apache.commons.math3.exception.NonMonotonicSequenceException; import org.apache.commons.math3.exception.NotPositiveException; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.util.MathArrays; import org.apache.commons.math3.util.Precision; import org.apache.commons.math3.optim.nonlinear.vector.jacobian.GaussNewtonOptimizer; import org.apache.commons.math3.fitting.PolynomialFitter; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; import org.apache.commons.math3.optim.SimpleVectorValueChecker; public class SmoothingPolynomialBicubicSplineInterpolator extends BicubicSplineInterpolator { private final PolynomialFitter xFitter; private final int xDegree; private final PolynomialFitter yFitter; private final int yDegree; public SmoothingPolynomialBicubicSplineInterpolator(); public SmoothingPolynomialBicubicSplineInterpolator(int degree) throws NotPositiveException; public SmoothingPolynomialBicubicSplineInterpolator(int xDegree, int yDegree) throws NotPositiveException; @Override public BicubicSplineInterpolatingFunction interpolate(final double[] xval, final double[] yval, final double[][] fval) throws NoDataException, NullArgumentException, DimensionMismatchException, NonMonotonicSequenceException; } // Abstract Java Test Class package org.apache.commons.math3.analysis.interpolation; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.analysis.BivariateFunction; import org.junit.Assert; import org.junit.Test; public final class SmoothingPolynomialBicubicSplineInterpolatorTest { @Test public void testPreconditions(); @Test public void testPlane(); @Test public void testParaboloid(); public double value(double x, double y); public double value(double x, double y); } ``` You are a professional Java test case writer, please create a test case named `testParaboloid` for the `SmoothingPolynomialBicubicSplineInterpolator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test of interpolator for a paraboloid. * <p> * z = 2 x<sup>2</sup> - 3 y<sup>2</sup> + 4 x y - 5 */ @Test public void testParaboloid() { ```
public class SmoothingPolynomialBicubicSplineInterpolator extends BicubicSplineInterpolator
package org.apache.commons.math3.analysis.interpolation; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.analysis.BivariateFunction; import org.junit.Assert; import org.junit.Test;
@Test public void testPreconditions(); @Test public void testPlane(); @Test public void testParaboloid(); public double value(double x, double y); public double value(double x, double y);
6874fcb80a83a231a65f8156d39a6448ff93d950d60a38b6c219b4eea1c18951
[ "org.apache.commons.math3.analysis.interpolation.SmoothingPolynomialBicubicSplineInterpolatorTest::testParaboloid" ]
private final PolynomialFitter xFitter; private final int xDegree; private final PolynomialFitter yFitter; private final int yDegree;
@Test public void testParaboloid()
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.interpolation; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.analysis.BivariateFunction; import org.junit.Assert; import org.junit.Test; /** * Test case for the smoothing bicubic interpolator. * * @version $Id$ */ public final class SmoothingPolynomialBicubicSplineInterpolatorTest { /** * Test preconditions. */ @Test public void testPreconditions() { double[] xval = new double[] {3, 4, 5, 6.5}; double[] yval = new double[] {-4, -3, -1, 2.5}; double[][] zval = new double[xval.length][yval.length]; BivariateGridInterpolator interpolator = new SmoothingPolynomialBicubicSplineInterpolator(0); @SuppressWarnings("unused") BivariateFunction p = interpolator.interpolate(xval, yval, zval); double[] wxval = new double[] {3, 2, 5, 6.5}; try { p = interpolator.interpolate(wxval, yval, zval); Assert.fail("an exception should have been thrown"); } catch (MathIllegalArgumentException e) { // Expected } double[] wyval = new double[] {-4, -3, -1, -1}; try { p = interpolator.interpolate(xval, wyval, zval); Assert.fail("an exception should have been thrown"); } catch (MathIllegalArgumentException e) { // Expected } double[][] wzval = new double[xval.length][yval.length + 1]; try { p = interpolator.interpolate(xval, yval, wzval); Assert.fail("an exception should have been thrown"); } catch (DimensionMismatchException e) { // Expected } wzval = new double[xval.length - 1][yval.length]; try { p = interpolator.interpolate(xval, yval, wzval); Assert.fail("an exception should have been thrown"); } catch (DimensionMismatchException e) { // Expected } wzval = new double[xval.length][yval.length - 1]; try { p = interpolator.interpolate(xval, yval, wzval); Assert.fail("an exception should have been thrown"); } catch (DimensionMismatchException e) { // Expected } } /** * Test of interpolator for a plane. * <p> * z = 2 x - 3 y + 5 */ @Test public void testPlane() { BivariateFunction f = new BivariateFunction() { public double value(double x, double y) { return 2 * x - 3 * y + 5 + ((int) (FastMath.abs(5 * x + 3 * y)) % 2 == 0 ? 1 : -1); } }; BivariateGridInterpolator interpolator = new SmoothingPolynomialBicubicSplineInterpolator(1); double[] xval = new double[] {3, 4, 5, 6.5}; double[] yval = new double[] {-4, -3, -1, 2, 2.5}; double[][] zval = new double[xval.length][yval.length]; for (int i = 0; i < xval.length; i++) { for (int j = 0; j < yval.length; j++) { zval[i][j] = f.value(xval[i], yval[j]); } } BivariateFunction p = interpolator.interpolate(xval, yval, zval); double x, y; double expected, result; x = 4; y = -3; expected = f.value(x, y); result = p.value(x, y); Assert.assertEquals("On sample point", expected, result, 2); x = 4.5; y = -1.5; expected = f.value(x, y); result = p.value(x, y); Assert.assertEquals("half-way between sample points (middle of the patch)", expected, result, 2); x = 3.5; y = -3.5; expected = f.value(x, y); result = p.value(x, y); Assert.assertEquals("half-way between sample points (border of the patch)", expected, result, 2); } /** * Test of interpolator for a paraboloid. * <p> * z = 2 x<sup>2</sup> - 3 y<sup>2</sup> + 4 x y - 5 */ @Test public void testParaboloid() { BivariateFunction f = new BivariateFunction() { public double value(double x, double y) { return 2 * x * x - 3 * y * y + 4 * x * y - 5 + ((int) (FastMath.abs(5 * x + 3 * y)) % 2 == 0 ? 1 : -1); } }; BivariateGridInterpolator interpolator = new SmoothingPolynomialBicubicSplineInterpolator(4); double[] xval = new double[] {3, 4, 5, 6.5}; double[] yval = new double[] {-4, -3, -2, -1, 0.5, 2.5}; double[][] zval = new double[xval.length][yval.length]; for (int i = 0; i < xval.length; i++) { for (int j = 0; j < yval.length; j++) { zval[i][j] = f.value(xval[i], yval[j]); } } BivariateFunction p = interpolator.interpolate(xval, yval, zval); double x, y; double expected, result; x = 5; y = 0.5; expected = f.value(x, y); result = p.value(x, y); Assert.assertEquals("On sample point", expected, result, 2); x = 4.5; y = -1.5; expected = f.value(x, y); result = p.value(x, y); Assert.assertEquals("half-way between sample points (middle of the patch)", expected, result, 2); x = 3.5; y = -3.5; expected = f.value(x, y); result = p.value(x, y); Assert.assertEquals("half-way between sample points (border of the patch)", expected, result, 2); } }
[ { "be_test_class_file": "org/apache/commons/math3/analysis/interpolation/SmoothingPolynomialBicubicSplineInterpolator.java", "be_test_class_name": "org.apache.commons.math3.analysis.interpolation.SmoothingPolynomialBicubicSplineInterpolator", "be_test_function_name": "interpolate", "be_test_function_signature": "([D[D[[D)Lorg/apache/commons/math3/analysis/BivariateFunction;", "line_numbers": [ "39" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/analysis/interpolation/SmoothingPolynomialBicubicSplineInterpolator.java", "be_test_class_name": "org.apache.commons.math3.analysis.interpolation.SmoothingPolynomialBicubicSplineInterpolator", "be_test_function_name": "interpolate", "be_test_function_signature": "([D[D[[D)Lorg/apache/commons/math3/analysis/interpolation/BicubicSplineInterpolatingFunction;", "line_numbers": [ "101", "102", "104", "105", "108", "109", "111", "112", "113", "117", "118", "122", "123", "124", "125", "126", "131", "136", "137", "138", "139", "140", "146", "147", "148", "149", "150", "155", "160", "161", "162", "163", "164", "168" ], "method_line_rate": 0.9117647058823529 } ]
public class BoundedIteratorTest<E> extends AbstractIteratorTest<E>
@Test public void testOffsetGreaterThanSize() { Iterator<E> iter = new BoundedIterator<E>(testList.iterator(), 10, 4); assertFalse(iter.hasNext()); try { iter.next(); fail("Expected NoSuchElementException."); } catch (NoSuchElementException nsee) { /* Success case */ } }
// // Abstract Java Tested Class // package org.apache.commons.collections4.iterators; // // import java.util.Iterator; // import java.util.NoSuchElementException; // // // // public class BoundedIterator<E> implements Iterator<E> { // private final Iterator<? extends E> iterator; // private final long offset; // private final long max; // private long pos; // // public BoundedIterator(final Iterator<? extends E> iterator, final long offset, final long max); // private void init(); // @Override // public boolean hasNext(); // private boolean checkBounds(); // @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 BoundedIteratorTest<E> extends AbstractIteratorTest<E> { // private final String[] testArray = { // "a", "b", "c", "d", "e", "f", "g" // }; // private List<E> testList; // // public BoundedIteratorTest(final String testName); // @SuppressWarnings("unchecked") // @Override // public void setUp() // throws Exception; // @Override // public Iterator<E> makeEmptyIterator(); // @Override // public Iterator<E> makeObject(); // @Test // public void testBounded(); // @Test // public void testSameAsDecorated(); // @Test // public void testEmptyBounded(); // @Test // public void testNegativeOffset(); // @Test // public void testNegativeMax(); // @Test // public void testOffsetGreaterThanSize(); // @Test // public void testMaxGreaterThanSize(); // @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 `testOffsetGreaterThanSize` for the `BoundedIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test the case if the <code>offset</code> passed to the constructor is * greater than the decorated iterator's size. The BoundedIterator should * behave as if there are no more elements to return. */
src/test/java/org/apache/commons/collections4/iterators/BoundedIteratorTest.java
package org.apache.commons.collections4.iterators; import java.util.Iterator; import java.util.NoSuchElementException;
public BoundedIterator(final Iterator<? extends E> iterator, final long offset, final long max); private void init(); @Override public boolean hasNext(); private boolean checkBounds(); @Override public E next(); @Override public void remove();
177
testOffsetGreaterThanSize
```java // Abstract Java Tested Class package org.apache.commons.collections4.iterators; import java.util.Iterator; import java.util.NoSuchElementException; public class BoundedIterator<E> implements Iterator<E> { private final Iterator<? extends E> iterator; private final long offset; private final long max; private long pos; public BoundedIterator(final Iterator<? extends E> iterator, final long offset, final long max); private void init(); @Override public boolean hasNext(); private boolean checkBounds(); @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 BoundedIteratorTest<E> extends AbstractIteratorTest<E> { private final String[] testArray = { "a", "b", "c", "d", "e", "f", "g" }; private List<E> testList; public BoundedIteratorTest(final String testName); @SuppressWarnings("unchecked") @Override public void setUp() throws Exception; @Override public Iterator<E> makeEmptyIterator(); @Override public Iterator<E> makeObject(); @Test public void testBounded(); @Test public void testSameAsDecorated(); @Test public void testEmptyBounded(); @Test public void testNegativeOffset(); @Test public void testNegativeMax(); @Test public void testOffsetGreaterThanSize(); @Test public void testMaxGreaterThanSize(); @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 `testOffsetGreaterThanSize` for the `BoundedIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test the case if the <code>offset</code> passed to the constructor is * greater than the decorated iterator's size. The BoundedIterator should * behave as if there are no more elements to return. */
168
// // Abstract Java Tested Class // package org.apache.commons.collections4.iterators; // // import java.util.Iterator; // import java.util.NoSuchElementException; // // // // public class BoundedIterator<E> implements Iterator<E> { // private final Iterator<? extends E> iterator; // private final long offset; // private final long max; // private long pos; // // public BoundedIterator(final Iterator<? extends E> iterator, final long offset, final long max); // private void init(); // @Override // public boolean hasNext(); // private boolean checkBounds(); // @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 BoundedIteratorTest<E> extends AbstractIteratorTest<E> { // private final String[] testArray = { // "a", "b", "c", "d", "e", "f", "g" // }; // private List<E> testList; // // public BoundedIteratorTest(final String testName); // @SuppressWarnings("unchecked") // @Override // public void setUp() // throws Exception; // @Override // public Iterator<E> makeEmptyIterator(); // @Override // public Iterator<E> makeObject(); // @Test // public void testBounded(); // @Test // public void testSameAsDecorated(); // @Test // public void testEmptyBounded(); // @Test // public void testNegativeOffset(); // @Test // public void testNegativeMax(); // @Test // public void testOffsetGreaterThanSize(); // @Test // public void testMaxGreaterThanSize(); // @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 `testOffsetGreaterThanSize` for the `BoundedIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test the case if the <code>offset</code> passed to the constructor is * greater than the decorated iterator's size. The BoundedIterator should * behave as if there are no more elements to return. */ @Test public void testOffsetGreaterThanSize() {
/** * Test the case if the <code>offset</code> passed to the constructor is * greater than the decorated iterator's size. The BoundedIterator should * behave as if there are no more elements to return. */
28
org.apache.commons.collections4.iterators.BoundedIterator
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.collections4.iterators; import java.util.Iterator; import java.util.NoSuchElementException; public class BoundedIterator<E> implements Iterator<E> { private final Iterator<? extends E> iterator; private final long offset; private final long max; private long pos; public BoundedIterator(final Iterator<? extends E> iterator, final long offset, final long max); private void init(); @Override public boolean hasNext(); private boolean checkBounds(); @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 BoundedIteratorTest<E> extends AbstractIteratorTest<E> { private final String[] testArray = { "a", "b", "c", "d", "e", "f", "g" }; private List<E> testList; public BoundedIteratorTest(final String testName); @SuppressWarnings("unchecked") @Override public void setUp() throws Exception; @Override public Iterator<E> makeEmptyIterator(); @Override public Iterator<E> makeObject(); @Test public void testBounded(); @Test public void testSameAsDecorated(); @Test public void testEmptyBounded(); @Test public void testNegativeOffset(); @Test public void testNegativeMax(); @Test public void testOffsetGreaterThanSize(); @Test public void testMaxGreaterThanSize(); @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 `testOffsetGreaterThanSize` for the `BoundedIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test the case if the <code>offset</code> passed to the constructor is * greater than the decorated iterator's size. The BoundedIterator should * behave as if there are no more elements to return. */ @Test public void testOffsetGreaterThanSize() { ```
public class BoundedIterator<E> implements Iterator<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 BoundedIteratorTest(final String testName); @SuppressWarnings("unchecked") @Override public void setUp() throws Exception; @Override public Iterator<E> makeEmptyIterator(); @Override public Iterator<E> makeObject(); @Test public void testBounded(); @Test public void testSameAsDecorated(); @Test public void testEmptyBounded(); @Test public void testNegativeOffset(); @Test public void testNegativeMax(); @Test public void testOffsetGreaterThanSize(); @Test public void testMaxGreaterThanSize(); @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();
691fa7d2362ce4ea94267b7147d03e020bf1f7cb752a6c0a3bcd954fae65f23f
[ "org.apache.commons.collections4.iterators.BoundedIteratorTest::testOffsetGreaterThanSize" ]
private final Iterator<? extends E> iterator; private final long offset; private final long max; private long pos;
@Test public void testOffsetGreaterThanSize()
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 BoundedIterator}. * * @version $Id$ */ public class BoundedIteratorTest<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 BoundedIteratorTest(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 BoundedIterator<E>(Collections.<E>emptyList().iterator(), 0, 10); } @Override public Iterator<E> makeObject() { return new BoundedIterator<E>(new ArrayList<E>(testList).iterator(), 1, testList.size() - 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 testBounded() { Iterator<E> iter = new BoundedIterator<E>(testList.iterator(), 2, 4); 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()); 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 and the <code>max</code> is its size, in that the BoundedIterator * should return all the same elements as its decorated iterator. */ @Test public void testSameAsDecorated() { Iterator<E> iter = new BoundedIterator<E>(testList.iterator(), 0, testList.size()); 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 a decorated iterator bounded to a <code>max</code> of 0. The * BoundedIterator should behave as if there are no more elements to return, * since it is technically an empty iterator. */ @Test public void testEmptyBounded() { Iterator<E> iter = new BoundedIterator<E>(testList.iterator(), 3, 0); 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 BoundedIterator<E>(testList.iterator(), -1, 4); fail("Expected IllegalArgumentException."); } catch (IllegalArgumentException iae) { /* Success case */ } } /** * Test the case if a negative <code>max</code> is passed to the * constructor. {@link IllegalArgumentException} is expected. */ @Test public void testNegativeMax() { try { new BoundedIterator<E>(testList.iterator(), 3, -1); fail("Expected IllegalArgumentException."); } catch (IllegalArgumentException iae) { /* Success case */ } } /** * Test the case if the <code>offset</code> passed to the constructor is * greater than the decorated iterator's size. The BoundedIterator should * behave as if there are no more elements to return. */ @Test public void testOffsetGreaterThanSize() { Iterator<E> iter = new BoundedIterator<E>(testList.iterator(), 10, 4); assertFalse(iter.hasNext()); try { iter.next(); fail("Expected NoSuchElementException."); } catch (NoSuchElementException nsee) { /* Success case */ } } /** * Test the case if the <code>max</code> passed to the constructor is * greater than the size of the decorated iterator. The last element * returned should be the same as the last element of the decorated * iterator. */ @Test public void testMaxGreaterThanSize() { Iterator<E> iter = new BoundedIterator<E>(testList.iterator(), 1, 10); 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 <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 BoundedIterator<E>(testListCopy.iterator(), 1, 5); 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 BoundedIterator<E>(testListCopy.iterator(), 1, 5); 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 BoundedIterator<E>(testListCopy.iterator(), 1, 5); assertTrue(iter.hasNext()); assertEquals("b", iter.next()); iter.remove(); assertFalse(testListCopy.contains("b")); 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()); 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 BoundedIterator<E>(testListCopy.iterator(), 1, 5); assertTrue(iter.hasNext()); assertEquals("b", iter.next()); assertTrue(iter.hasNext()); assertEquals("c", iter.next()); 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()); 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 BoundedIterator<E>(testListCopy.iterator(), 1, 5); 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()); assertFalse(iter.hasNext()); try { iter.next(); fail("Expected NoSuchElementException."); } catch (NoSuchElementException nsee) { /* Success case */ } iter.remove(); assertFalse(testListCopy.contains("f")); 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 BoundedIterator<E>(mockIterator, 1, 5); 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/BoundedIterator.java", "be_test_class_name": "org.apache.commons.collections4.iterators.BoundedIterator", "be_test_function_name": "checkBounds", "be_test_function_signature": "()Z", "line_numbers": [ "106", "107", "109" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "org/apache/commons/collections4/iterators/BoundedIterator.java", "be_test_class_name": "org.apache.commons.collections4.iterators.BoundedIterator", "be_test_function_name": "hasNext", "be_test_function_signature": "()Z", "line_numbers": [ "95", "96", "98" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "org/apache/commons/collections4/iterators/BoundedIterator.java", "be_test_class_name": "org.apache.commons.collections4.iterators.BoundedIterator", "be_test_function_name": "init", "be_test_function_signature": "()V", "line_numbers": [ "85", "86", "87", "89" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/collections4/iterators/BoundedIterator.java", "be_test_class_name": "org.apache.commons.collections4.iterators.BoundedIterator", "be_test_function_name": "next", "be_test_function_signature": "()Ljava/lang/Object;", "line_numbers": [ "114", "115", "117", "118", "119" ], "method_line_rate": 0.4 } ]
public class StatisticalBarRendererTests extends TestCase
public void testDrawWithNullMeanVertical() { boolean success = false; try { DefaultStatisticalCategoryDataset dataset = new DefaultStatisticalCategoryDataset(); dataset.add(1.0, 2.0, "S1", "C1"); dataset.add(null, new Double(4.0), "S1", "C2"); CategoryPlot plot = new CategoryPlot(dataset, new CategoryAxis("Category"), new NumberAxis("Value"), new StatisticalBarRenderer()); JFreeChart chart = new JFreeChart(plot); /* BufferedImage image = */ chart.createBufferedImage(300, 200, null); success = true; } catch (NullPointerException e) { e.printStackTrace(); success = false; } assertTrue(success); }
// // Abstract Java Tested Class // package org.jfree.chart.renderer.category; // // import java.awt.BasicStroke; // import java.awt.Color; // import java.awt.GradientPaint; // import java.awt.Graphics2D; // import java.awt.Paint; // import java.awt.Stroke; // import java.awt.geom.Line2D; // import java.awt.geom.Rectangle2D; // import java.io.IOException; // import java.io.ObjectInputStream; // import java.io.ObjectOutputStream; // import java.io.Serializable; // import org.jfree.chart.axis.CategoryAxis; // import org.jfree.chart.axis.ValueAxis; // import org.jfree.chart.entity.EntityCollection; // import org.jfree.chart.event.RendererChangeEvent; // import org.jfree.chart.labels.CategoryItemLabelGenerator; // import org.jfree.chart.plot.CategoryPlot; // import org.jfree.chart.plot.PlotOrientation; // import org.jfree.chart.util.GradientPaintTransformer; // 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.SerialUtilities; // import org.jfree.data.Range; // import org.jfree.data.category.CategoryDataset; // import org.jfree.data.statistics.StatisticalCategoryDataset; // // // // public class StatisticalBarRenderer extends BarRenderer // implements CategoryItemRenderer, Cloneable, PublicCloneable, // Serializable { // private static final long serialVersionUID = -4986038395414039117L; // private transient Paint errorIndicatorPaint; // private transient Stroke errorIndicatorStroke; // // public StatisticalBarRenderer(); // public Paint getErrorIndicatorPaint(); // public void setErrorIndicatorPaint(Paint paint); // public Stroke getErrorIndicatorStroke(); // public void setErrorIndicatorStroke(Stroke stroke); // public Range findRangeBounds(CategoryDataset dataset); // public void drawItem(Graphics2D g2, CategoryItemRendererState state, // Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, // ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, // boolean selected, int pass); // protected void drawHorizontalItem(Graphics2D g2, // CategoryItemRendererState state, Rectangle2D dataArea, // CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, // StatisticalCategoryDataset dataset, int visibleRow, // int row, int column, boolean selected); // protected void drawVerticalItem(Graphics2D g2, // CategoryItemRendererState state, Rectangle2D dataArea, // CategoryPlot plot,CategoryAxis domainAxis,ValueAxis rangeAxis, // StatisticalCategoryDataset dataset, int visibleRow, // int row, int column, boolean selected); // public boolean equals(Object obj); // private void writeObject(ObjectOutputStream stream) throws IOException; // private void readObject(ObjectInputStream stream) // throws IOException, ClassNotFoundException; // } // // // Abstract Java Test Class // package org.jfree.chart.renderer.category.junit; // // import java.awt.BasicStroke; // import java.awt.Color; // 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.chart.JFreeChart; // import org.jfree.chart.axis.CategoryAxis; // import org.jfree.chart.axis.NumberAxis; // import org.jfree.chart.plot.CategoryPlot; // import org.jfree.chart.plot.PlotOrientation; // import org.jfree.chart.renderer.category.StatisticalBarRenderer; // import org.jfree.chart.util.PublicCloneable; // import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; // // // // public class StatisticalBarRendererTests extends TestCase { // // // public static Test suite(); // public StatisticalBarRendererTests(String name); // public void testEquals(); // public void testHashcode(); // public void testCloning(); // public void testPublicCloneable(); // public void testSerialization(); // public void testDrawWithNullInfo(); // public void testDrawWithNullMeanVertical(); // public void testDrawWithNullMeanHorizontal(); // public void testDrawWithNullDeviationVertical(); // public void testDrawWithNullDeviationHorizontal(); // } // You are a professional Java test case writer, please create a test case named `testDrawWithNullMeanVertical` for the `StatisticalBarRenderer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Draws the chart with a <code>null</code> mean value to make sure that * no exceptions are thrown (particularly by code in the renderer). See * bug report 1779941. */
tests/org/jfree/chart/renderer/category/junit/StatisticalBarRendererTests.java
package org.jfree.chart.renderer.category; import java.awt.BasicStroke; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.CategoryItemLabelGenerator; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.util.GradientPaintTransformer; 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.SerialUtilities; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.statistics.StatisticalCategoryDataset;
public StatisticalBarRenderer(); public Paint getErrorIndicatorPaint(); public void setErrorIndicatorPaint(Paint paint); public Stroke getErrorIndicatorStroke(); public void setErrorIndicatorStroke(Stroke stroke); public Range findRangeBounds(CategoryDataset dataset); public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, boolean selected, int pass); protected void drawHorizontalItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, StatisticalCategoryDataset dataset, int visibleRow, int row, int column, boolean selected); protected void drawVerticalItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot,CategoryAxis domainAxis,ValueAxis rangeAxis, StatisticalCategoryDataset dataset, int visibleRow, int row, int column, boolean selected); public boolean equals(Object obj); private void writeObject(ObjectOutputStream stream) throws IOException; private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException;
223
testDrawWithNullMeanVertical
```java // Abstract Java Tested Class package org.jfree.chart.renderer.category; import java.awt.BasicStroke; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.CategoryItemLabelGenerator; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.util.GradientPaintTransformer; 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.SerialUtilities; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.statistics.StatisticalCategoryDataset; public class StatisticalBarRenderer extends BarRenderer implements CategoryItemRenderer, Cloneable, PublicCloneable, Serializable { private static final long serialVersionUID = -4986038395414039117L; private transient Paint errorIndicatorPaint; private transient Stroke errorIndicatorStroke; public StatisticalBarRenderer(); public Paint getErrorIndicatorPaint(); public void setErrorIndicatorPaint(Paint paint); public Stroke getErrorIndicatorStroke(); public void setErrorIndicatorStroke(Stroke stroke); public Range findRangeBounds(CategoryDataset dataset); public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, boolean selected, int pass); protected void drawHorizontalItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, StatisticalCategoryDataset dataset, int visibleRow, int row, int column, boolean selected); protected void drawVerticalItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot,CategoryAxis domainAxis,ValueAxis rangeAxis, StatisticalCategoryDataset dataset, int visibleRow, int row, int column, boolean selected); public boolean equals(Object obj); private void writeObject(ObjectOutputStream stream) throws IOException; private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException; } // Abstract Java Test Class package org.jfree.chart.renderer.category.junit; import java.awt.BasicStroke; import java.awt.Color; 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.chart.JFreeChart; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.category.StatisticalBarRenderer; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; public class StatisticalBarRendererTests extends TestCase { public static Test suite(); public StatisticalBarRendererTests(String name); public void testEquals(); public void testHashcode(); public void testCloning(); public void testPublicCloneable(); public void testSerialization(); public void testDrawWithNullInfo(); public void testDrawWithNullMeanVertical(); public void testDrawWithNullMeanHorizontal(); public void testDrawWithNullDeviationVertical(); public void testDrawWithNullDeviationHorizontal(); } ``` You are a professional Java test case writer, please create a test case named `testDrawWithNullMeanVertical` for the `StatisticalBarRenderer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Draws the chart with a <code>null</code> mean value to make sure that * no exceptions are thrown (particularly by code in the renderer). See * bug report 1779941. */
203
// // Abstract Java Tested Class // package org.jfree.chart.renderer.category; // // import java.awt.BasicStroke; // import java.awt.Color; // import java.awt.GradientPaint; // import java.awt.Graphics2D; // import java.awt.Paint; // import java.awt.Stroke; // import java.awt.geom.Line2D; // import java.awt.geom.Rectangle2D; // import java.io.IOException; // import java.io.ObjectInputStream; // import java.io.ObjectOutputStream; // import java.io.Serializable; // import org.jfree.chart.axis.CategoryAxis; // import org.jfree.chart.axis.ValueAxis; // import org.jfree.chart.entity.EntityCollection; // import org.jfree.chart.event.RendererChangeEvent; // import org.jfree.chart.labels.CategoryItemLabelGenerator; // import org.jfree.chart.plot.CategoryPlot; // import org.jfree.chart.plot.PlotOrientation; // import org.jfree.chart.util.GradientPaintTransformer; // 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.SerialUtilities; // import org.jfree.data.Range; // import org.jfree.data.category.CategoryDataset; // import org.jfree.data.statistics.StatisticalCategoryDataset; // // // // public class StatisticalBarRenderer extends BarRenderer // implements CategoryItemRenderer, Cloneable, PublicCloneable, // Serializable { // private static final long serialVersionUID = -4986038395414039117L; // private transient Paint errorIndicatorPaint; // private transient Stroke errorIndicatorStroke; // // public StatisticalBarRenderer(); // public Paint getErrorIndicatorPaint(); // public void setErrorIndicatorPaint(Paint paint); // public Stroke getErrorIndicatorStroke(); // public void setErrorIndicatorStroke(Stroke stroke); // public Range findRangeBounds(CategoryDataset dataset); // public void drawItem(Graphics2D g2, CategoryItemRendererState state, // Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, // ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, // boolean selected, int pass); // protected void drawHorizontalItem(Graphics2D g2, // CategoryItemRendererState state, Rectangle2D dataArea, // CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, // StatisticalCategoryDataset dataset, int visibleRow, // int row, int column, boolean selected); // protected void drawVerticalItem(Graphics2D g2, // CategoryItemRendererState state, Rectangle2D dataArea, // CategoryPlot plot,CategoryAxis domainAxis,ValueAxis rangeAxis, // StatisticalCategoryDataset dataset, int visibleRow, // int row, int column, boolean selected); // public boolean equals(Object obj); // private void writeObject(ObjectOutputStream stream) throws IOException; // private void readObject(ObjectInputStream stream) // throws IOException, ClassNotFoundException; // } // // // Abstract Java Test Class // package org.jfree.chart.renderer.category.junit; // // import java.awt.BasicStroke; // import java.awt.Color; // 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.chart.JFreeChart; // import org.jfree.chart.axis.CategoryAxis; // import org.jfree.chart.axis.NumberAxis; // import org.jfree.chart.plot.CategoryPlot; // import org.jfree.chart.plot.PlotOrientation; // import org.jfree.chart.renderer.category.StatisticalBarRenderer; // import org.jfree.chart.util.PublicCloneable; // import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; // // // // public class StatisticalBarRendererTests extends TestCase { // // // public static Test suite(); // public StatisticalBarRendererTests(String name); // public void testEquals(); // public void testHashcode(); // public void testCloning(); // public void testPublicCloneable(); // public void testSerialization(); // public void testDrawWithNullInfo(); // public void testDrawWithNullMeanVertical(); // public void testDrawWithNullMeanHorizontal(); // public void testDrawWithNullDeviationVertical(); // public void testDrawWithNullDeviationHorizontal(); // } // You are a professional Java test case writer, please create a test case named `testDrawWithNullMeanVertical` for the `StatisticalBarRenderer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Draws the chart with a <code>null</code> mean value to make sure that * no exceptions are thrown (particularly by code in the renderer). See * bug report 1779941. */ public void testDrawWithNullMeanVertical() {
/** * Draws the chart with a <code>null</code> mean value to make sure that * no exceptions are thrown (particularly by code in the renderer). See * bug report 1779941. */
1
org.jfree.chart.renderer.category.StatisticalBarRenderer
tests
```java // Abstract Java Tested Class package org.jfree.chart.renderer.category; import java.awt.BasicStroke; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.labels.CategoryItemLabelGenerator; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.util.GradientPaintTransformer; 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.SerialUtilities; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.statistics.StatisticalCategoryDataset; public class StatisticalBarRenderer extends BarRenderer implements CategoryItemRenderer, Cloneable, PublicCloneable, Serializable { private static final long serialVersionUID = -4986038395414039117L; private transient Paint errorIndicatorPaint; private transient Stroke errorIndicatorStroke; public StatisticalBarRenderer(); public Paint getErrorIndicatorPaint(); public void setErrorIndicatorPaint(Paint paint); public Stroke getErrorIndicatorStroke(); public void setErrorIndicatorStroke(Stroke stroke); public Range findRangeBounds(CategoryDataset dataset); public void drawItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryDataset dataset, int row, int column, boolean selected, int pass); protected void drawHorizontalItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot, CategoryAxis domainAxis, ValueAxis rangeAxis, StatisticalCategoryDataset dataset, int visibleRow, int row, int column, boolean selected); protected void drawVerticalItem(Graphics2D g2, CategoryItemRendererState state, Rectangle2D dataArea, CategoryPlot plot,CategoryAxis domainAxis,ValueAxis rangeAxis, StatisticalCategoryDataset dataset, int visibleRow, int row, int column, boolean selected); public boolean equals(Object obj); private void writeObject(ObjectOutputStream stream) throws IOException; private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException; } // Abstract Java Test Class package org.jfree.chart.renderer.category.junit; import java.awt.BasicStroke; import java.awt.Color; 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.chart.JFreeChart; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.category.StatisticalBarRenderer; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; public class StatisticalBarRendererTests extends TestCase { public static Test suite(); public StatisticalBarRendererTests(String name); public void testEquals(); public void testHashcode(); public void testCloning(); public void testPublicCloneable(); public void testSerialization(); public void testDrawWithNullInfo(); public void testDrawWithNullMeanVertical(); public void testDrawWithNullMeanHorizontal(); public void testDrawWithNullDeviationVertical(); public void testDrawWithNullDeviationHorizontal(); } ``` You are a professional Java test case writer, please create a test case named `testDrawWithNullMeanVertical` for the `StatisticalBarRenderer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Draws the chart with a <code>null</code> mean value to make sure that * no exceptions are thrown (particularly by code in the renderer). See * bug report 1779941. */ public void testDrawWithNullMeanVertical() { ```
public class StatisticalBarRenderer extends BarRenderer implements CategoryItemRenderer, Cloneable, PublicCloneable, Serializable
package org.jfree.chart.renderer.category.junit; import java.awt.BasicStroke; import java.awt.Color; 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.chart.JFreeChart; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.category.StatisticalBarRenderer; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.statistics.DefaultStatisticalCategoryDataset;
public static Test suite(); public StatisticalBarRendererTests(String name); public void testEquals(); public void testHashcode(); public void testCloning(); public void testPublicCloneable(); public void testSerialization(); public void testDrawWithNullInfo(); public void testDrawWithNullMeanVertical(); public void testDrawWithNullMeanHorizontal(); public void testDrawWithNullDeviationVertical(); public void testDrawWithNullDeviationHorizontal();
6fce6b428373f91dfa85e8ba241c374fa059d6a3d3ae5eeddd78046d9456841f
[ "org.jfree.chart.renderer.category.junit.StatisticalBarRendererTests::testDrawWithNullMeanVertical" ]
private static final long serialVersionUID = -4986038395414039117L; private transient Paint errorIndicatorPaint; private transient Stroke errorIndicatorStroke;
public void testDrawWithNullMeanVertical()
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.] * * -------------------------------- * StatisticalBarRendererTests.java * -------------------------------- * (C) Copyright 2003-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 25-Mar-2003 : Version 1 (DG); * 28-Aug-2007 : Added tests for bug 1779941 (DG); * 14-Nov-2007 : Updated testEquals() (DG); * 23-Apr-2008 : Added testPublicCloneable() (DG); * */ package org.jfree.chart.renderer.category.junit; import java.awt.BasicStroke; import java.awt.Color; 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.chart.JFreeChart; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.category.StatisticalBarRenderer; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; /** * Tests for the {@link StatisticalBarRenderer} class. */ public class StatisticalBarRendererTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(StatisticalBarRendererTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public StatisticalBarRendererTests(String name) { super(name); } /** * Check that the equals() method distinguishes all fields. */ public void testEquals() { StatisticalBarRenderer r1 = new StatisticalBarRenderer(); StatisticalBarRenderer r2 = new StatisticalBarRenderer(); assertEquals(r1, r2); r1.setErrorIndicatorPaint(Color.red); assertFalse(r1.equals(r2)); r2.setErrorIndicatorPaint(Color.red); assertTrue(r2.equals(r1)); r1.setErrorIndicatorStroke(new BasicStroke(1.5f)); assertFalse(r1.equals(r2)); r2.setErrorIndicatorStroke(new BasicStroke(1.5f)); assertTrue(r2.equals(r1)); } /** * Two objects that are equal are required to return the same hashCode. */ public void testHashcode() { StatisticalBarRenderer r1 = new StatisticalBarRenderer(); StatisticalBarRenderer r2 = new StatisticalBarRenderer(); assertTrue(r1.equals(r2)); int h1 = r1.hashCode(); int h2 = r2.hashCode(); assertEquals(h1, h2); } /** * Confirm that cloning works. */ public void testCloning() { StatisticalBarRenderer r1 = new StatisticalBarRenderer(); StatisticalBarRenderer r2 = null; try { r2 = (StatisticalBarRenderer) r1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(r1 != r2); assertTrue(r1.getClass() == r2.getClass()); assertTrue(r1.equals(r2)); } /** * Check that this class implements PublicCloneable. */ public void testPublicCloneable() { StatisticalBarRenderer r1 = new StatisticalBarRenderer(); assertTrue(r1 instanceof PublicCloneable); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { StatisticalBarRenderer r1 = new StatisticalBarRenderer(); StatisticalBarRenderer r2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(r1); out.close(); ObjectInput in = new ObjectInputStream(new ByteArrayInputStream( buffer.toByteArray())); r2 = (StatisticalBarRenderer) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(r1, r2); } /** * Draws the chart with a <code>null</code> info object to make sure that * no exceptions are thrown (particularly by code in the renderer). */ public void testDrawWithNullInfo() { boolean success = false; try { DefaultStatisticalCategoryDataset dataset = new DefaultStatisticalCategoryDataset(); dataset.add(1.0, 2.0, "S1", "C1"); dataset.add(3.0, 4.0, "S1", "C2"); CategoryPlot plot = new CategoryPlot(dataset, new CategoryAxis("Category"), new NumberAxis("Value"), new StatisticalBarRenderer()); JFreeChart chart = new JFreeChart(plot); /* BufferedImage image = */ chart.createBufferedImage(300, 200, null); success = true; } catch (NullPointerException e) { e.printStackTrace(); success = false; } assertTrue(success); } /** * Draws the chart with a <code>null</code> mean value to make sure that * no exceptions are thrown (particularly by code in the renderer). See * bug report 1779941. */ public void testDrawWithNullMeanVertical() { boolean success = false; try { DefaultStatisticalCategoryDataset dataset = new DefaultStatisticalCategoryDataset(); dataset.add(1.0, 2.0, "S1", "C1"); dataset.add(null, new Double(4.0), "S1", "C2"); CategoryPlot plot = new CategoryPlot(dataset, new CategoryAxis("Category"), new NumberAxis("Value"), new StatisticalBarRenderer()); JFreeChart chart = new JFreeChart(plot); /* BufferedImage image = */ chart.createBufferedImage(300, 200, null); success = true; } catch (NullPointerException e) { e.printStackTrace(); success = false; } assertTrue(success); } /** * Draws the chart with a <code>null</code> mean value to make sure that * no exceptions are thrown (particularly by code in the renderer). See * bug report 1779941. */ public void testDrawWithNullMeanHorizontal() { boolean success = false; try { DefaultStatisticalCategoryDataset dataset = new DefaultStatisticalCategoryDataset(); dataset.add(1.0, 2.0, "S1", "C1"); dataset.add(null, new Double(4.0), "S1", "C2"); CategoryPlot plot = new CategoryPlot(dataset, new CategoryAxis("Category"), new NumberAxis("Value"), new StatisticalBarRenderer()); plot.setOrientation(PlotOrientation.HORIZONTAL); JFreeChart chart = new JFreeChart(plot); /* BufferedImage image = */ chart.createBufferedImage(300, 200, null); success = true; } catch (NullPointerException e) { e.printStackTrace(); success = false; } assertTrue(success); } /** * Draws the chart with a <code>null</code> standard deviation to make sure * that no exceptions are thrown (particularly by code in the renderer). * See bug report 1779941. */ public void testDrawWithNullDeviationVertical() { boolean success = false; try { DefaultStatisticalCategoryDataset dataset = new DefaultStatisticalCategoryDataset(); dataset.add(1.0, 2.0, "S1", "C1"); dataset.add(new Double(4.0), null, "S1", "C2"); CategoryPlot plot = new CategoryPlot(dataset, new CategoryAxis("Category"), new NumberAxis("Value"), new StatisticalBarRenderer()); JFreeChart chart = new JFreeChart(plot); /* BufferedImage image = */ chart.createBufferedImage(300, 200, null); success = true; } catch (NullPointerException e) { e.printStackTrace(); success = false; } assertTrue(success); } /** * Draws the chart with a <code>null</code> standard deviation to make sure * that no exceptions are thrown (particularly by code in the renderer). * See bug report 1779941. */ public void testDrawWithNullDeviationHorizontal() { boolean success = false; try { DefaultStatisticalCategoryDataset dataset = new DefaultStatisticalCategoryDataset(); dataset.add(1.0, 2.0, "S1", "C1"); dataset.add(new Double(4.0), null, "S1", "C2"); CategoryPlot plot = new CategoryPlot(dataset, new CategoryAxis("Category"), new NumberAxis("Value"), new StatisticalBarRenderer()); plot.setOrientation(PlotOrientation.HORIZONTAL); JFreeChart chart = new JFreeChart(plot); /* BufferedImage image = */ chart.createBufferedImage(300, 200, null); success = true; } catch (NullPointerException e) { e.printStackTrace(); success = false; } assertTrue(success); } }
[ { "be_test_class_file": "org/jfree/chart/renderer/category/StatisticalBarRenderer.java", "be_test_class_name": "org.jfree.chart.renderer.category.StatisticalBarRenderer", "be_test_function_name": "drawItem", "be_test_function_signature": "(Ljava/awt/Graphics2D;Lorg/jfree/chart/renderer/category/CategoryItemRendererState;Ljava/awt/geom/Rectangle2D;Lorg/jfree/chart/plot/CategoryPlot;Lorg/jfree/chart/axis/CategoryAxis;Lorg/jfree/chart/axis/ValueAxis;Lorg/jfree/data/category/CategoryDataset;IIZI)V", "line_numbers": [ "224", "225", "226", "229", "230", "233", "236", "237", "238", "241", "242", "245" ], "method_line_rate": 0.75 }, { "be_test_class_file": "org/jfree/chart/renderer/category/StatisticalBarRenderer.java", "be_test_class_name": "org.jfree.chart.renderer.category.StatisticalBarRenderer", "be_test_function_name": "drawVerticalItem", "be_test_function_signature": "(Ljava/awt/Graphics2D;Lorg/jfree/chart/renderer/category/CategoryItemRendererState;Ljava/awt/geom/Rectangle2D;Lorg/jfree/chart/plot/CategoryPlot;Lorg/jfree/chart/axis/CategoryAxis;Lorg/jfree/chart/axis/ValueAxis;Lorg/jfree/data/statistics/StatisticalCategoryDataset;IIIZ)V", "line_numbers": [ "429", "432", "435", "437", "438", "439", "441", "442", "444", "448", "449", "450", "453", "454", "455", "456", "458", "459", "460", "462", "463", "464", "467", "468", "469", "472", "473", "478", "479", "481", "482", "483", "487", "488", "489", "491", "493", "494", "496", "498", "499", "500", "501", "503", "504", "506", "508", "509", "510", "511", "512", "513", "518", "519", "520", "521", "523", "526", "527", "530", "532", "533", "536", "539", "540", "542", "543", "545", "546", "548", "551", "553", "554", "559", "560", "561", "563" ], "method_line_rate": 0.6623376623376623 }, { "be_test_class_file": "org/jfree/chart/renderer/category/StatisticalBarRenderer.java", "be_test_class_name": "org.jfree.chart.renderer.category.StatisticalBarRenderer", "be_test_function_name": "findRangeBounds", "be_test_function_signature": "(Lorg/jfree/data/category/CategoryDataset;)Lorg/jfree/data/Range;", "line_numbers": [ "200" ], "method_line_rate": 1 } ]
public class SegmentedTimelineTests extends TestCase
public void testBasicSegmentedTimeline() { SegmentedTimeline stl = new SegmentedTimeline(10, 2, 3); stl.setStartTime(946684800000L); // 1-Jan-2000 assertFalse(stl.containsDomainValue(946684799999L)); assertTrue(stl.containsDomainValue(946684800000L)); assertTrue(stl.containsDomainValue(946684800019L)); assertFalse(stl.containsDomainValue(946684800020L)); assertFalse(stl.containsDomainValue(946684800049L)); assertTrue(stl.containsDomainValue(946684800050L)); assertTrue(stl.containsDomainValue(946684800069L)); assertFalse(stl.containsDomainValue(946684800070L)); assertFalse(stl.containsDomainValue(946684800099L)); assertTrue(stl.containsDomainValue(946684800100L)); assertEquals(0, stl.toTimelineValue(946684800000L)); assertEquals(19, stl.toTimelineValue(946684800019L)); assertEquals(20, stl.toTimelineValue(946684800020L)); assertEquals(20, stl.toTimelineValue(946684800049L)); assertEquals(20, stl.toTimelineValue(946684800050L)); assertEquals(39, stl.toTimelineValue(946684800069L)); assertEquals(40, stl.toTimelineValue(946684800070L)); assertEquals(40, stl.toTimelineValue(946684800099L)); assertEquals(40, stl.toTimelineValue(946684800100L)); assertEquals(946684800000L, stl.toMillisecond(0)); assertEquals(946684800019L, stl.toMillisecond(19)); assertEquals(946684800050L, stl.toMillisecond(20)); assertEquals(946684800069L, stl.toMillisecond(39)); assertEquals(946684800100L, stl.toMillisecond(40)); }
// "2000-12-25", "2001-01-01", "2001-01-15", "2001-02-19", "2001-04-13", // "2001-05-28", "2001-07-04", "2001-09-03", "2001-09-11", "2001-09-12", // "2001-09-13", "2001-09-14", "2001-11-22", "2001-12-25", "2002-01-01", // "2002-01-21", "2002-02-18", "2002-03-29", "2002-05-27", "2002-07-04", // "2002-09-02", "2002-11-28", "2002-12-25"}; // private static final String[] FIFTEEN_MIN_EXCEPTIONS = { // "2000-01-10 09:00:00", "2000-01-10 09:15:00", "2000-01-10 09:30:00", // "2000-01-10 09:45:00", "2000-01-10 10:00:00", "2000-01-10 10:15:00", // "2000-02-15 09:00:00", "2000-02-15 09:15:00", "2000-02-15 09:30:00", // "2000-02-15 09:45:00", "2000-02-15 10:00:00", "2000-02-15 10:15:00", // "2000-02-16 11:00:00", "2000-02-16 11:15:00", "2000-02-16 11:30:00", // "2000-02-16 11:45:00", "2000-02-16 12:00:00", "2000-02-16 12:15:00", // "2000-02-16 12:30:00", "2000-02-16 12:45:00", "2000-02-16 01:00:00", // "2000-02-16 01:15:00", "2000-02-16 01:30:00", "2000-02-16 01:45:00", // "2000-05-17 11:45:00", "2000-05-17 12:00:00", "2000-05-17 12:15:00", // "2000-05-17 12:30:00", "2000-05-17 12:45:00", "2000-05-17 01:00:00", // "2000-05-17 01:15:00", "2000-05-17 01:30:00", "2000-05-17 01:45:00", // "2000-05-17 02:00:00", "2000-05-17 02:15:00", "2000-05-17 02:30:00", // "2000-05-17 02:45:00", "2000-05-17 03:00:00", "2000-05-17 03:15:00", // "2000-05-17 03:30:00", "2000-05-17 03:45:00", "2000-05-17 04:00:00"}; // private SegmentedTimeline msTimeline; // private SegmentedTimeline ms2Timeline; // private SegmentedTimeline ms2BaseTimeline; // private SegmentedTimeline mondayFridayTimeline; // private SegmentedTimeline fifteenMinTimeline; // private Calendar monday; // private Calendar monday9am; // // public static Test suite(); // public SegmentedTimelineTests(String name); // protected void setUp() throws Exception; // protected void tearDown() throws Exception; // public void testMsSegmentedTimeline(); // public void testMs2SegmentedTimeline(); // public void testMondayThroughFridaySegmentedTimeline(); // public void testFifteenMinSegmentedTimeline(); // public void testMsSegment(); // public void testMs2Segment(); // public void testMondayThroughFridaySegment(); // public void testFifteenMinSegment(); // public void verifyOneSegment(SegmentedTimeline timeline); // public void testMsInc(); // public void testMs2Inc(); // public void testMondayThroughFridayInc(); // public void testFifteenMinInc(); // public void verifyInc(SegmentedTimeline timeline); // public void testMsIncludedAndExcludedSegments(); // public void testMs2IncludedAndExcludedSegments(); // public void testMondayThroughFridayIncludedAndExcludedSegments(); // public void testFifteenMinIncludedAndExcludedSegments(); // public void verifyIncludedAndExcludedSegments(SegmentedTimeline timeline, // long n); // public void testMsExceptionSegments() throws ParseException; // public void testMs2BaseTimelineExceptionSegments() throws ParseException; // public void testMondayThoughFridayExceptionSegments() // throws ParseException; // public void testFifteenMinExceptionSegments() throws ParseException; // public void verifyExceptionSegments(SegmentedTimeline timeline, // String[] exceptionString, // Format fmt) // throws ParseException; // public void testMsTranslations() throws ParseException; // public void testMs2BaseTimelineTranslations() throws ParseException; // public void testMs2Translations() throws ParseException; // public void textMondayThroughFridayTranslations() throws ParseException; // public void testFifteenMinTranslations() throws ParseException; // public void verifyTranslations(SegmentedTimeline timeline, long startTest); // public void testSerialization(); // private void verifySerialization(SegmentedTimeline a1); // private long[] verifyFillInExceptions(SegmentedTimeline timeline, // String[] exceptionString, // Format fmt) throws ParseException; // private void fillInBaseTimelineExceptions(SegmentedTimeline timeline, // String[] exceptionString, // Format fmt) throws ParseException; // private void fillInBaseTimelineExclusionsAsExceptions( // SegmentedTimeline timeline, long from, long to); // public void testCloning(); // public void testEquals(); // public void testHashCode(); // public void testSerialization2(); // public void testBasicSegmentedTimeline(); // public void testSegmentedTimelineWithException1(); // public static void main(String[] args) throws Exception; // } // You are a professional Java test case writer, please create a test case named `testBasicSegmentedTimeline` for the `SegmentedTimeline` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests a basic segmented timeline. */
tests/org/jfree/chart/axis/junit/SegmentedTimelineTests.java
package org.jfree.chart.axis; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.SimpleTimeZone; import java.util.TimeZone;
public SegmentedTimeline(long segmentSize, int segmentsIncluded, int segmentsExcluded); public static long firstMondayAfter1900(); public static SegmentedTimeline newMondayThroughFridayTimeline(); public static SegmentedTimeline newFifteenMinuteTimeline(); public boolean getAdjustForDaylightSaving(); public void setAdjustForDaylightSaving(boolean adjust); public void setStartTime(long millisecond); public long getStartTime(); public int getSegmentsExcluded(); public long getSegmentsExcludedSize(); public int getGroupSegmentCount(); public long getSegmentsGroupSize(); public int getSegmentsIncluded(); public long getSegmentsIncludedSize(); public long getSegmentSize(); public List getExceptionSegments(); public void setExceptionSegments(List exceptionSegments); public SegmentedTimeline getBaseTimeline(); public void setBaseTimeline(SegmentedTimeline baseTimeline); public long toTimelineValue(long millisecond); public long toTimelineValue(Date date); public long toMillisecond(long timelineValue); public long getTimeFromLong(long date); public boolean containsDomainValue(long millisecond); public boolean containsDomainValue(Date date); public boolean containsDomainRange(long domainValueStart, long domainValueEnd); public boolean containsDomainRange(Date dateDomainValueStart, Date dateDomainValueEnd); public void addException(long millisecond); public void addException(long fromDomainValue, long toDomainValue); public void addException(Date exceptionDate); public void addExceptions(List exceptionList); private void addException(Segment segment); public void addBaseTimelineException(long domainValue); public void addBaseTimelineException(Date date); public void addBaseTimelineExclusions(long fromBaseDomainValue, long toBaseDomainValue); public long getExceptionSegmentCount(long fromMillisecond, long toMillisecond); public Segment getSegment(long millisecond); public Segment getSegment(Date date); private boolean equals(Object o, Object p); public boolean equals(Object o); public int hashCode(); private int binarySearchExceptionSegments(Segment segment); public long getTime(Date date); public Date getDate(long value); public Object clone() throws CloneNotSupportedException; protected Segment(); protected Segment(long millisecond); public long calculateSegmentNumber(long millis); public long getSegmentNumber(); public long getSegmentCount(); public long getSegmentStart(); public long getSegmentEnd(); public long getMillisecond(); public Date getDate(); public boolean contains(long millis); public boolean contains(long from, long to); public boolean contains(Segment segment); public boolean contained(long from, long to); public Segment intersect(long from, long to); public boolean before(Segment other); public boolean after(Segment other); public boolean equals(Object object); public Segment copy(); public int compareTo(Object object); public boolean inIncludeSegments(); public boolean inExcludeSegments(); private long getSegmentNumberRelativeToGroup(); public boolean inExceptionSegments(); public void inc(long n); public void inc(); public void dec(long n); public void dec(); public void moveIndexToStart(); public void moveIndexToEnd(); public SegmentRange(long fromMillisecond, long toMillisecond); public long getSegmentCount(); public Segment intersect(long from, long to); public boolean inIncludeSegments(); public boolean inExcludeSegments(); public void inc(long n); public BaseTimelineSegmentRange(long fromDomainValue, long toDomainValue);
1,102
testBasicSegmentedTimeline
```java "2000-12-25", "2001-01-01", "2001-01-15", "2001-02-19", "2001-04-13", "2001-05-28", "2001-07-04", "2001-09-03", "2001-09-11", "2001-09-12", "2001-09-13", "2001-09-14", "2001-11-22", "2001-12-25", "2002-01-01", "2002-01-21", "2002-02-18", "2002-03-29", "2002-05-27", "2002-07-04", "2002-09-02", "2002-11-28", "2002-12-25"}; private static final String[] FIFTEEN_MIN_EXCEPTIONS = { "2000-01-10 09:00:00", "2000-01-10 09:15:00", "2000-01-10 09:30:00", "2000-01-10 09:45:00", "2000-01-10 10:00:00", "2000-01-10 10:15:00", "2000-02-15 09:00:00", "2000-02-15 09:15:00", "2000-02-15 09:30:00", "2000-02-15 09:45:00", "2000-02-15 10:00:00", "2000-02-15 10:15:00", "2000-02-16 11:00:00", "2000-02-16 11:15:00", "2000-02-16 11:30:00", "2000-02-16 11:45:00", "2000-02-16 12:00:00", "2000-02-16 12:15:00", "2000-02-16 12:30:00", "2000-02-16 12:45:00", "2000-02-16 01:00:00", "2000-02-16 01:15:00", "2000-02-16 01:30:00", "2000-02-16 01:45:00", "2000-05-17 11:45:00", "2000-05-17 12:00:00", "2000-05-17 12:15:00", "2000-05-17 12:30:00", "2000-05-17 12:45:00", "2000-05-17 01:00:00", "2000-05-17 01:15:00", "2000-05-17 01:30:00", "2000-05-17 01:45:00", "2000-05-17 02:00:00", "2000-05-17 02:15:00", "2000-05-17 02:30:00", "2000-05-17 02:45:00", "2000-05-17 03:00:00", "2000-05-17 03:15:00", "2000-05-17 03:30:00", "2000-05-17 03:45:00", "2000-05-17 04:00:00"}; private SegmentedTimeline msTimeline; private SegmentedTimeline ms2Timeline; private SegmentedTimeline ms2BaseTimeline; private SegmentedTimeline mondayFridayTimeline; private SegmentedTimeline fifteenMinTimeline; private Calendar monday; private Calendar monday9am; public static Test suite(); public SegmentedTimelineTests(String name); protected void setUp() throws Exception; protected void tearDown() throws Exception; public void testMsSegmentedTimeline(); public void testMs2SegmentedTimeline(); public void testMondayThroughFridaySegmentedTimeline(); public void testFifteenMinSegmentedTimeline(); public void testMsSegment(); public void testMs2Segment(); public void testMondayThroughFridaySegment(); public void testFifteenMinSegment(); public void verifyOneSegment(SegmentedTimeline timeline); public void testMsInc(); public void testMs2Inc(); public void testMondayThroughFridayInc(); public void testFifteenMinInc(); public void verifyInc(SegmentedTimeline timeline); public void testMsIncludedAndExcludedSegments(); public void testMs2IncludedAndExcludedSegments(); public void testMondayThroughFridayIncludedAndExcludedSegments(); public void testFifteenMinIncludedAndExcludedSegments(); public void verifyIncludedAndExcludedSegments(SegmentedTimeline timeline, long n); public void testMsExceptionSegments() throws ParseException; public void testMs2BaseTimelineExceptionSegments() throws ParseException; public void testMondayThoughFridayExceptionSegments() throws ParseException; public void testFifteenMinExceptionSegments() throws ParseException; public void verifyExceptionSegments(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException; public void testMsTranslations() throws ParseException; public void testMs2BaseTimelineTranslations() throws ParseException; public void testMs2Translations() throws ParseException; public void textMondayThroughFridayTranslations() throws ParseException; public void testFifteenMinTranslations() throws ParseException; public void verifyTranslations(SegmentedTimeline timeline, long startTest); public void testSerialization(); private void verifySerialization(SegmentedTimeline a1); private long[] verifyFillInExceptions(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException; private void fillInBaseTimelineExceptions(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException; private void fillInBaseTimelineExclusionsAsExceptions( SegmentedTimeline timeline, long from, long to); public void testCloning(); public void testEquals(); public void testHashCode(); public void testSerialization2(); public void testBasicSegmentedTimeline(); public void testSegmentedTimelineWithException1(); public static void main(String[] args) throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testBasicSegmentedTimeline` for the `SegmentedTimeline` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests a basic segmented timeline. */
1,072
// "2000-12-25", "2001-01-01", "2001-01-15", "2001-02-19", "2001-04-13", // "2001-05-28", "2001-07-04", "2001-09-03", "2001-09-11", "2001-09-12", // "2001-09-13", "2001-09-14", "2001-11-22", "2001-12-25", "2002-01-01", // "2002-01-21", "2002-02-18", "2002-03-29", "2002-05-27", "2002-07-04", // "2002-09-02", "2002-11-28", "2002-12-25"}; // private static final String[] FIFTEEN_MIN_EXCEPTIONS = { // "2000-01-10 09:00:00", "2000-01-10 09:15:00", "2000-01-10 09:30:00", // "2000-01-10 09:45:00", "2000-01-10 10:00:00", "2000-01-10 10:15:00", // "2000-02-15 09:00:00", "2000-02-15 09:15:00", "2000-02-15 09:30:00", // "2000-02-15 09:45:00", "2000-02-15 10:00:00", "2000-02-15 10:15:00", // "2000-02-16 11:00:00", "2000-02-16 11:15:00", "2000-02-16 11:30:00", // "2000-02-16 11:45:00", "2000-02-16 12:00:00", "2000-02-16 12:15:00", // "2000-02-16 12:30:00", "2000-02-16 12:45:00", "2000-02-16 01:00:00", // "2000-02-16 01:15:00", "2000-02-16 01:30:00", "2000-02-16 01:45:00", // "2000-05-17 11:45:00", "2000-05-17 12:00:00", "2000-05-17 12:15:00", // "2000-05-17 12:30:00", "2000-05-17 12:45:00", "2000-05-17 01:00:00", // "2000-05-17 01:15:00", "2000-05-17 01:30:00", "2000-05-17 01:45:00", // "2000-05-17 02:00:00", "2000-05-17 02:15:00", "2000-05-17 02:30:00", // "2000-05-17 02:45:00", "2000-05-17 03:00:00", "2000-05-17 03:15:00", // "2000-05-17 03:30:00", "2000-05-17 03:45:00", "2000-05-17 04:00:00"}; // private SegmentedTimeline msTimeline; // private SegmentedTimeline ms2Timeline; // private SegmentedTimeline ms2BaseTimeline; // private SegmentedTimeline mondayFridayTimeline; // private SegmentedTimeline fifteenMinTimeline; // private Calendar monday; // private Calendar monday9am; // // public static Test suite(); // public SegmentedTimelineTests(String name); // protected void setUp() throws Exception; // protected void tearDown() throws Exception; // public void testMsSegmentedTimeline(); // public void testMs2SegmentedTimeline(); // public void testMondayThroughFridaySegmentedTimeline(); // public void testFifteenMinSegmentedTimeline(); // public void testMsSegment(); // public void testMs2Segment(); // public void testMondayThroughFridaySegment(); // public void testFifteenMinSegment(); // public void verifyOneSegment(SegmentedTimeline timeline); // public void testMsInc(); // public void testMs2Inc(); // public void testMondayThroughFridayInc(); // public void testFifteenMinInc(); // public void verifyInc(SegmentedTimeline timeline); // public void testMsIncludedAndExcludedSegments(); // public void testMs2IncludedAndExcludedSegments(); // public void testMondayThroughFridayIncludedAndExcludedSegments(); // public void testFifteenMinIncludedAndExcludedSegments(); // public void verifyIncludedAndExcludedSegments(SegmentedTimeline timeline, // long n); // public void testMsExceptionSegments() throws ParseException; // public void testMs2BaseTimelineExceptionSegments() throws ParseException; // public void testMondayThoughFridayExceptionSegments() // throws ParseException; // public void testFifteenMinExceptionSegments() throws ParseException; // public void verifyExceptionSegments(SegmentedTimeline timeline, // String[] exceptionString, // Format fmt) // throws ParseException; // public void testMsTranslations() throws ParseException; // public void testMs2BaseTimelineTranslations() throws ParseException; // public void testMs2Translations() throws ParseException; // public void textMondayThroughFridayTranslations() throws ParseException; // public void testFifteenMinTranslations() throws ParseException; // public void verifyTranslations(SegmentedTimeline timeline, long startTest); // public void testSerialization(); // private void verifySerialization(SegmentedTimeline a1); // private long[] verifyFillInExceptions(SegmentedTimeline timeline, // String[] exceptionString, // Format fmt) throws ParseException; // private void fillInBaseTimelineExceptions(SegmentedTimeline timeline, // String[] exceptionString, // Format fmt) throws ParseException; // private void fillInBaseTimelineExclusionsAsExceptions( // SegmentedTimeline timeline, long from, long to); // public void testCloning(); // public void testEquals(); // public void testHashCode(); // public void testSerialization2(); // public void testBasicSegmentedTimeline(); // public void testSegmentedTimelineWithException1(); // public static void main(String[] args) throws Exception; // } // You are a professional Java test case writer, please create a test case named `testBasicSegmentedTimeline` for the `SegmentedTimeline` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests a basic segmented timeline. */ ////////////////////////////////////////////////////////////////////////// // utility methods ////////////////////////////////////////////////////////////////////////// public void testBasicSegmentedTimeline() {
/** * Tests a basic segmented timeline. */ ////////////////////////////////////////////////////////////////////////// // utility methods //////////////////////////////////////////////////////////////////////////
1
org.jfree.chart.axis.SegmentedTimeline
tests
```java "2000-12-25", "2001-01-01", "2001-01-15", "2001-02-19", "2001-04-13", "2001-05-28", "2001-07-04", "2001-09-03", "2001-09-11", "2001-09-12", "2001-09-13", "2001-09-14", "2001-11-22", "2001-12-25", "2002-01-01", "2002-01-21", "2002-02-18", "2002-03-29", "2002-05-27", "2002-07-04", "2002-09-02", "2002-11-28", "2002-12-25"}; private static final String[] FIFTEEN_MIN_EXCEPTIONS = { "2000-01-10 09:00:00", "2000-01-10 09:15:00", "2000-01-10 09:30:00", "2000-01-10 09:45:00", "2000-01-10 10:00:00", "2000-01-10 10:15:00", "2000-02-15 09:00:00", "2000-02-15 09:15:00", "2000-02-15 09:30:00", "2000-02-15 09:45:00", "2000-02-15 10:00:00", "2000-02-15 10:15:00", "2000-02-16 11:00:00", "2000-02-16 11:15:00", "2000-02-16 11:30:00", "2000-02-16 11:45:00", "2000-02-16 12:00:00", "2000-02-16 12:15:00", "2000-02-16 12:30:00", "2000-02-16 12:45:00", "2000-02-16 01:00:00", "2000-02-16 01:15:00", "2000-02-16 01:30:00", "2000-02-16 01:45:00", "2000-05-17 11:45:00", "2000-05-17 12:00:00", "2000-05-17 12:15:00", "2000-05-17 12:30:00", "2000-05-17 12:45:00", "2000-05-17 01:00:00", "2000-05-17 01:15:00", "2000-05-17 01:30:00", "2000-05-17 01:45:00", "2000-05-17 02:00:00", "2000-05-17 02:15:00", "2000-05-17 02:30:00", "2000-05-17 02:45:00", "2000-05-17 03:00:00", "2000-05-17 03:15:00", "2000-05-17 03:30:00", "2000-05-17 03:45:00", "2000-05-17 04:00:00"}; private SegmentedTimeline msTimeline; private SegmentedTimeline ms2Timeline; private SegmentedTimeline ms2BaseTimeline; private SegmentedTimeline mondayFridayTimeline; private SegmentedTimeline fifteenMinTimeline; private Calendar monday; private Calendar monday9am; public static Test suite(); public SegmentedTimelineTests(String name); protected void setUp() throws Exception; protected void tearDown() throws Exception; public void testMsSegmentedTimeline(); public void testMs2SegmentedTimeline(); public void testMondayThroughFridaySegmentedTimeline(); public void testFifteenMinSegmentedTimeline(); public void testMsSegment(); public void testMs2Segment(); public void testMondayThroughFridaySegment(); public void testFifteenMinSegment(); public void verifyOneSegment(SegmentedTimeline timeline); public void testMsInc(); public void testMs2Inc(); public void testMondayThroughFridayInc(); public void testFifteenMinInc(); public void verifyInc(SegmentedTimeline timeline); public void testMsIncludedAndExcludedSegments(); public void testMs2IncludedAndExcludedSegments(); public void testMondayThroughFridayIncludedAndExcludedSegments(); public void testFifteenMinIncludedAndExcludedSegments(); public void verifyIncludedAndExcludedSegments(SegmentedTimeline timeline, long n); public void testMsExceptionSegments() throws ParseException; public void testMs2BaseTimelineExceptionSegments() throws ParseException; public void testMondayThoughFridayExceptionSegments() throws ParseException; public void testFifteenMinExceptionSegments() throws ParseException; public void verifyExceptionSegments(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException; public void testMsTranslations() throws ParseException; public void testMs2BaseTimelineTranslations() throws ParseException; public void testMs2Translations() throws ParseException; public void textMondayThroughFridayTranslations() throws ParseException; public void testFifteenMinTranslations() throws ParseException; public void verifyTranslations(SegmentedTimeline timeline, long startTest); public void testSerialization(); private void verifySerialization(SegmentedTimeline a1); private long[] verifyFillInExceptions(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException; private void fillInBaseTimelineExceptions(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException; private void fillInBaseTimelineExclusionsAsExceptions( SegmentedTimeline timeline, long from, long to); public void testCloning(); public void testEquals(); public void testHashCode(); public void testSerialization2(); public void testBasicSegmentedTimeline(); public void testSegmentedTimelineWithException1(); public static void main(String[] args) throws Exception; } ``` You are a professional Java test case writer, please create a test case named `testBasicSegmentedTimeline` for the `SegmentedTimeline` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests a basic segmented timeline. */ ////////////////////////////////////////////////////////////////////////// // utility methods ////////////////////////////////////////////////////////////////////////// public void testBasicSegmentedTimeline() { ```
public class SegmentedTimeline implements Timeline, Cloneable, Serializable
package org.jfree.chart.axis.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 java.text.Format; import java.text.NumberFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Iterator; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.axis.SegmentedTimeline;
public static Test suite(); public SegmentedTimelineTests(String name); protected void setUp() throws Exception; protected void tearDown() throws Exception; public void testMsSegmentedTimeline(); public void testMs2SegmentedTimeline(); public void testMondayThroughFridaySegmentedTimeline(); public void testFifteenMinSegmentedTimeline(); public void testMsSegment(); public void testMs2Segment(); public void testMondayThroughFridaySegment(); public void testFifteenMinSegment(); public void verifyOneSegment(SegmentedTimeline timeline); public void testMsInc(); public void testMs2Inc(); public void testMondayThroughFridayInc(); public void testFifteenMinInc(); public void verifyInc(SegmentedTimeline timeline); public void testMsIncludedAndExcludedSegments(); public void testMs2IncludedAndExcludedSegments(); public void testMondayThroughFridayIncludedAndExcludedSegments(); public void testFifteenMinIncludedAndExcludedSegments(); public void verifyIncludedAndExcludedSegments(SegmentedTimeline timeline, long n); public void testMsExceptionSegments() throws ParseException; public void testMs2BaseTimelineExceptionSegments() throws ParseException; public void testMondayThoughFridayExceptionSegments() throws ParseException; public void testFifteenMinExceptionSegments() throws ParseException; public void verifyExceptionSegments(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException; public void testMsTranslations() throws ParseException; public void testMs2BaseTimelineTranslations() throws ParseException; public void testMs2Translations() throws ParseException; public void textMondayThroughFridayTranslations() throws ParseException; public void testFifteenMinTranslations() throws ParseException; public void verifyTranslations(SegmentedTimeline timeline, long startTest); public void testSerialization(); private void verifySerialization(SegmentedTimeline a1); private long[] verifyFillInExceptions(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException; private void fillInBaseTimelineExceptions(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException; private void fillInBaseTimelineExclusionsAsExceptions( SegmentedTimeline timeline, long from, long to); public void testCloning(); public void testEquals(); public void testHashCode(); public void testSerialization2(); public void testBasicSegmentedTimeline(); public void testSegmentedTimelineWithException1(); public static void main(String[] args) throws Exception;
71fbed0b4385ae5ec64d255703ad7ed9877376daec17f220b823dba6700de86d
[ "org.jfree.chart.axis.junit.SegmentedTimelineTests::testBasicSegmentedTimeline" ]
private static final long serialVersionUID = 1093779862539903110L; public static final long DAY_SEGMENT_SIZE = 24 * 60 * 60 * 1000; public static final long HOUR_SEGMENT_SIZE = 60 * 60 * 1000; public static final long FIFTEEN_MINUTE_SEGMENT_SIZE = 15 * 60 * 1000; public static final long MINUTE_SEGMENT_SIZE = 60 * 1000; public static long FIRST_MONDAY_AFTER_1900; public static TimeZone NO_DST_TIME_ZONE; public static TimeZone DEFAULT_TIME_ZONE = TimeZone.getDefault(); private Calendar workingCalendarNoDST; private Calendar workingCalendar = Calendar.getInstance(); private long segmentSize; private int segmentsIncluded; private int segmentsExcluded; private int groupSegmentCount; private long startTime; private long segmentsIncludedSize; private long segmentsExcludedSize; private long segmentsGroupSize; private List exceptionSegments = new ArrayList(); private SegmentedTimeline baseTimeline; private boolean adjustForDaylightSaving = false;
public void testBasicSegmentedTimeline()
private static final int TEST_CYCLE_START = 0; private static final int TEST_CYCLE_END = 1000; private static final int TEST_CYCLE_INC = 55; private static final long FIVE_YEARS = 5 * 365 * SegmentedTimeline.DAY_SEGMENT_SIZE; private static final NumberFormat NUMBER_FORMAT = NumberFormat.getNumberInstance(); private static final SimpleDateFormat DATE_FORMAT; private static final SimpleDateFormat DATE_TIME_FORMAT; private static final String[] MS_EXCEPTIONS = {"0", "2", "4", "10", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "47", "58", "100", "101"}; private static final String[] MS2_BASE_TIMELINE_EXCEPTIONS = {"0", "8", "16", "24", "32", "40", "48", "56", "64", "72", "80", "88", "96", "104", "112", "120", "128", "136"}; private static final String[] US_HOLIDAYS = {"2000-01-17", "2000-02-21", "2000-04-21", "2000-05-29", "2000-07-04", "2000-09-04", "2000-11-23", "2000-12-25", "2001-01-01", "2001-01-15", "2001-02-19", "2001-04-13", "2001-05-28", "2001-07-04", "2001-09-03", "2001-09-11", "2001-09-12", "2001-09-13", "2001-09-14", "2001-11-22", "2001-12-25", "2002-01-01", "2002-01-21", "2002-02-18", "2002-03-29", "2002-05-27", "2002-07-04", "2002-09-02", "2002-11-28", "2002-12-25"}; private static final String[] FIFTEEN_MIN_EXCEPTIONS = { "2000-01-10 09:00:00", "2000-01-10 09:15:00", "2000-01-10 09:30:00", "2000-01-10 09:45:00", "2000-01-10 10:00:00", "2000-01-10 10:15:00", "2000-02-15 09:00:00", "2000-02-15 09:15:00", "2000-02-15 09:30:00", "2000-02-15 09:45:00", "2000-02-15 10:00:00", "2000-02-15 10:15:00", "2000-02-16 11:00:00", "2000-02-16 11:15:00", "2000-02-16 11:30:00", "2000-02-16 11:45:00", "2000-02-16 12:00:00", "2000-02-16 12:15:00", "2000-02-16 12:30:00", "2000-02-16 12:45:00", "2000-02-16 01:00:00", "2000-02-16 01:15:00", "2000-02-16 01:30:00", "2000-02-16 01:45:00", "2000-05-17 11:45:00", "2000-05-17 12:00:00", "2000-05-17 12:15:00", "2000-05-17 12:30:00", "2000-05-17 12:45:00", "2000-05-17 01:00:00", "2000-05-17 01:15:00", "2000-05-17 01:30:00", "2000-05-17 01:45:00", "2000-05-17 02:00:00", "2000-05-17 02:15:00", "2000-05-17 02:30:00", "2000-05-17 02:45:00", "2000-05-17 03:00:00", "2000-05-17 03:15:00", "2000-05-17 03:30:00", "2000-05-17 03:45:00", "2000-05-17 04:00:00"}; private SegmentedTimeline msTimeline; private SegmentedTimeline ms2Timeline; private SegmentedTimeline ms2BaseTimeline; private SegmentedTimeline mondayFridayTimeline; private SegmentedTimeline fifteenMinTimeline; private Calendar monday; private Calendar monday9am;
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.] * * ---------------------------- * SegmentedTimelineTests.java * ---------------------------- * (C) Copyright 2003-2008, by Bill Kelemen and Contributors. * * Original Author: Bill Kelemen; * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes * ------- * 24-May-2003 : Version 1 (BK); * 07-Jan-2005 : Added test for hashCode() method (DG); * 02-Feb-2007 : Removed author tags all over JFreeChart sources (DG); * */ package org.jfree.chart.axis.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 java.text.Format; import java.text.NumberFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Iterator; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.axis.SegmentedTimeline; /** * JUnit Tests for the {@link SegmentedTimeline} class. */ public class SegmentedTimelineTests extends TestCase { /** These constants control test cycles in the validateXXXX methods. */ private static final int TEST_CYCLE_START = 0; /** These constants control test cycles in the validateXXXX methods. */ private static final int TEST_CYCLE_END = 1000; /** These constants control test cycles in the validateXXXX methods. */ private static final int TEST_CYCLE_INC = 55; /** Number of ms in five years */ private static final long FIVE_YEARS = 5 * 365 * SegmentedTimeline.DAY_SEGMENT_SIZE; /** Number format object for ms tests. */ private static final NumberFormat NUMBER_FORMAT = NumberFormat.getNumberInstance(); /** Date format object for Monday through Friday tests. */ private static final SimpleDateFormat DATE_FORMAT; /** Date format object 9:00 AM to 4:00 PM tests. */ private static final SimpleDateFormat DATE_TIME_FORMAT; /** Some ms exceptions for ms testing. */ private static final String[] MS_EXCEPTIONS = {"0", "2", "4", "10", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "47", "58", "100", "101"}; /** Some ms4 exceptions for ms testing. */ private static final String[] MS2_BASE_TIMELINE_EXCEPTIONS = {"0", "8", "16", "24", "32", "40", "48", "56", "64", "72", "80", "88", "96", "104", "112", "120", "128", "136"}; /** US non-trading dates in 2000 through 2002 to test exceptions. */ private static final String[] US_HOLIDAYS = {"2000-01-17", "2000-02-21", "2000-04-21", "2000-05-29", "2000-07-04", "2000-09-04", "2000-11-23", "2000-12-25", "2001-01-01", "2001-01-15", "2001-02-19", "2001-04-13", "2001-05-28", "2001-07-04", "2001-09-03", "2001-09-11", "2001-09-12", "2001-09-13", "2001-09-14", "2001-11-22", "2001-12-25", "2002-01-01", "2002-01-21", "2002-02-18", "2002-03-29", "2002-05-27", "2002-07-04", "2002-09-02", "2002-11-28", "2002-12-25"}; /** Some test exceptions for the fifteen min timeline. */ private static final String[] FIFTEEN_MIN_EXCEPTIONS = { "2000-01-10 09:00:00", "2000-01-10 09:15:00", "2000-01-10 09:30:00", "2000-01-10 09:45:00", "2000-01-10 10:00:00", "2000-01-10 10:15:00", "2000-02-15 09:00:00", "2000-02-15 09:15:00", "2000-02-15 09:30:00", "2000-02-15 09:45:00", "2000-02-15 10:00:00", "2000-02-15 10:15:00", "2000-02-16 11:00:00", "2000-02-16 11:15:00", "2000-02-16 11:30:00", "2000-02-16 11:45:00", "2000-02-16 12:00:00", "2000-02-16 12:15:00", "2000-02-16 12:30:00", "2000-02-16 12:45:00", "2000-02-16 01:00:00", "2000-02-16 01:15:00", "2000-02-16 01:30:00", "2000-02-16 01:45:00", "2000-05-17 11:45:00", "2000-05-17 12:00:00", "2000-05-17 12:15:00", "2000-05-17 12:30:00", "2000-05-17 12:45:00", "2000-05-17 01:00:00", "2000-05-17 01:15:00", "2000-05-17 01:30:00", "2000-05-17 01:45:00", "2000-05-17 02:00:00", "2000-05-17 02:15:00", "2000-05-17 02:30:00", "2000-05-17 02:45:00", "2000-05-17 03:00:00", "2000-05-17 03:15:00", "2000-05-17 03:30:00", "2000-05-17 03:45:00", "2000-05-17 04:00:00"}; /** Our 1-ms test timeline using 5 included and 2 excluded segments. */ private SegmentedTimeline msTimeline; /** * Our 1-ms test timeline (with baseTimeline) using 2 included and 2 * excluded segments. */ private SegmentedTimeline ms2Timeline; /** * Our 4-ms test base timeline for ms2Timeline using 1 included and 1 * excluded segments */ private SegmentedTimeline ms2BaseTimeline; /** Our test Monday through Friday test timeline. */ private SegmentedTimeline mondayFridayTimeline; /** Our 9:00 AM to 4:00 PM fifteen minute timeline. */ private SegmentedTimeline fifteenMinTimeline; /** ms from 1970-01-01 to first monday after 2001-01-01. */ private Calendar monday; /** ms from 1970-01-01 to 9 am first monday after 2001-01-01. */ private Calendar monday9am; /** Static initialization block. */ static { DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); DATE_FORMAT.setTimeZone(SegmentedTimeline.NO_DST_TIME_ZONE); DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); DATE_TIME_FORMAT.setTimeZone(SegmentedTimeline.NO_DST_TIME_ZONE); } /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(SegmentedTimelineTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public SegmentedTimelineTests(String name) { super(name); } /** * Sets up the fixture, for example, open a network connection. * This method is called before a test is executed. * * @throws Exception if there is a problem. */ protected void setUp() throws Exception { // setup our test timelines // // Legend for comments below: // <spaces> = Segments included in the final timeline // EE = Excluded segments via timeline rules // xx = Exception segments inherited from base timeline exclusions // 1-ms test timeline using 5 included and 2 excluded segments. // // timeline start time = 0 // | // v // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 .. // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+.. // | | | | | |EE|EE| | | | | |EE|EE| | | | | | |EE|EE| <-- msTimeline // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+.. // \_________ ________/ \_/ // \/ | // segment group segment size = 1 ms // this.msTimeline = new SegmentedTimeline(1, 5, 2); this.msTimeline.setStartTime(0); // 4-ms test base timeline for ms2Timeline using 1 included and 1 // excluded segments // // timeline start time = 0 // | // v // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ... // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+... // | | | | |EE|EE|EE|EE| | | | |EE|EE|EE|EE| | | | | <-- ms2BaseTimeline // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+... // \__________ _________/ \____ _____/ // \/ \/ // segment group segment size = 4 ms // this.ms2BaseTimeline = new SegmentedTimeline(4, 1, 1); this.ms2BaseTimeline.setStartTime(0); // 1-ms test timeline (with a baseTimeline) using 2 included and 2 // excluded segments centered inside each base segment // // The ms2Timeline without a base would look like this: // // timeline start time = 1 // | // v // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ... // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+... // |EE| | |EE|EE| | |EE|EE| | |EE|EE| | |EE|EE| | |EE| <-- ms2Timeline // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+... // \____ _____/ \_/ // \/ | // segment group segment size = 1 ms // // With the base timeline some originally included segments are now // removed (see "xx" below): // // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ... // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+... // |EE| | |EE|EE|xx|xx|EE|EE| | |EE|EE|xx|xx|EE|EE| | |EE| <-- ms2Timeline // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+... // | | | | |EE|EE|EE|EE| | | | |EE|EE|EE|EE| | | | | <-- ms2BaseTimeline // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+... // this.ms2Timeline = new SegmentedTimeline(1, 2, 2); this.ms2Timeline.setStartTime(1); this.ms2Timeline.setBaseTimeline(this.ms2BaseTimeline); // test monday though friday timeline this.mondayFridayTimeline = SegmentedTimeline.newMondayThroughFridayTimeline(); // test 9am-4pm Monday through Friday timeline this.fifteenMinTimeline = SegmentedTimeline.newFifteenMinuteTimeline(); // find first Monday after 2001-01-01 Calendar cal = new GregorianCalendar( SegmentedTimeline.NO_DST_TIME_ZONE); cal.set(2001, 0, 1, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) { cal.add(Calendar.DATE, 1); } this.monday = (Calendar) cal.clone(); // calculate 9am on the first Monday after 2001-01-01 cal.add(Calendar.HOUR, 9); this.monday9am = (Calendar) cal.clone(); } /** * Tears down the fixture, for example, close a network connection. * This method is called after a test is executed. * * @throws Exception if there is a problem. */ protected void tearDown() throws Exception { // does nothing } ////////////////////////////////////////////////////////////////////////// // test construction process ////////////////////////////////////////////////////////////////////////// /** * Tests that the new method that created the msTimeline segmented * timeline did so correctly. */ public void testMsSegmentedTimeline() { // verify attributes set during object construction assertEquals(1, this.msTimeline.getSegmentSize()); assertEquals(0, this.msTimeline.getStartTime()); assertEquals(5, this.msTimeline.getSegmentsIncluded()); assertEquals(2, this.msTimeline.getSegmentsExcluded()); } /** * Tests that the new method that created the ms2Timeline segmented * timeline did so correctly. */ public void testMs2SegmentedTimeline() { // verify attributes set during object construction assertEquals(1, this.ms2Timeline.getSegmentSize()); assertEquals(1, this.ms2Timeline.getStartTime()); assertEquals(2, this.ms2Timeline.getSegmentsIncluded()); assertEquals(2, this.ms2Timeline.getSegmentsExcluded()); assertEquals(this.ms2BaseTimeline, this.ms2Timeline.getBaseTimeline()); } /** * Tests that the factory method that creates Monday through Friday * segmented timeline does so correctly. */ public void testMondayThroughFridaySegmentedTimeline() { // verify attributes set during object construction assertEquals(SegmentedTimeline.DAY_SEGMENT_SIZE, this.mondayFridayTimeline.getSegmentSize()); assertEquals(SegmentedTimeline.FIRST_MONDAY_AFTER_1900, this.mondayFridayTimeline.getStartTime()); assertEquals(5, this.mondayFridayTimeline.getSegmentsIncluded()); assertEquals(2, this.mondayFridayTimeline.getSegmentsExcluded()); } /** * Tests that the factory method that creates a 15-min 9:00 AM 4:00 PM * segmented axis does so correctly. */ public void testFifteenMinSegmentedTimeline() { assertEquals(SegmentedTimeline.FIFTEEN_MINUTE_SEGMENT_SIZE, this.fifteenMinTimeline.getSegmentSize()); assertEquals(SegmentedTimeline.FIRST_MONDAY_AFTER_1900 + 36 * this.fifteenMinTimeline.getSegmentSize(), this.fifteenMinTimeline.getStartTime()); assertEquals(28, this.fifteenMinTimeline.getSegmentsIncluded()); assertEquals(68, this.fifteenMinTimeline.getSegmentsExcluded()); } ////////////////////////////////////////////////////////////////////////// // test one-segment and adjacent segments ////////////////////////////////////////////////////////////////////////// /** * Tests one segment of the ms timeline. Internal indices * inside one segment as well as adjacent segments are verified. */ public void testMsSegment() { verifyOneSegment(this.msTimeline); } /** * Tests one segment of the ms timeline. Internal indices * inside one segment as well as adjacent segments are verified. */ public void testMs2Segment() { verifyOneSegment(this.ms2Timeline); } /** * Tests one segment of the Monday through Friday timeline. Internal indices * inside one segment as well as adjacent segments are verified. */ public void testMondayThroughFridaySegment() { verifyOneSegment(this.mondayFridayTimeline); } /** * Tests one segment of the Fifteen timeline. Internal indices * inside one segment as well as adjacent segments are verified. */ public void testFifteenMinSegment() { verifyOneSegment(this.fifteenMinTimeline); } /** * Tests one segment of the Monday through Friday timeline. Internal indices * inside one segment as well as adjacent segments are verified. * @param timeline the timeline to use for verifications. */ public void verifyOneSegment(SegmentedTimeline timeline) { for (long testCycle = TEST_CYCLE_START; testCycle < TEST_CYCLE_END; testCycle += TEST_CYCLE_INC) { // get two consecutive segments for various tests SegmentedTimeline.Segment segment1 = timeline.getSegment( this.monday.getTime().getTime() + testCycle); SegmentedTimeline.Segment segment2 = timeline.getSegment( segment1.getSegmentEnd() + 1); // verify segments are consecutive and correct assertEquals(segment1.getSegmentNumber() + 1, segment2.getSegmentNumber()); assertEquals(segment1.getSegmentEnd() + 1, segment2.getSegmentStart()); assertEquals(segment1.getSegmentStart() + timeline.getSegmentSize() - 1, segment1.getSegmentEnd()); assertEquals(segment1.getSegmentStart() + timeline.getSegmentSize(), segment2.getSegmentStart()); assertEquals(segment1.getSegmentEnd() + timeline.getSegmentSize(), segment2.getSegmentEnd()); // verify various indices inside a segment are the same segment long delta; if (timeline.getSegmentSize() > 1000000) { delta = timeline.getSegmentSize() / 10000; } else if (timeline.getSegmentSize() > 100000) { delta = timeline.getSegmentSize() / 1000; } else if (timeline.getSegmentSize() > 10000) { delta = timeline.getSegmentSize() / 100; } else if (timeline.getSegmentSize() > 1000) { delta = timeline.getSegmentSize() / 10; } else if (timeline.getSegmentSize() > 100) { delta = timeline.getSegmentSize() / 5; } else { delta = 1; } long start = segment1.getSegmentStart() + delta; long end = segment1.getSegmentStart() + timeline.getSegmentSize() - 1; SegmentedTimeline.Segment lastSeg = timeline.getSegment( segment1.getSegmentStart()); SegmentedTimeline.Segment seg; for (long i = start; i < end; i += delta) { seg = timeline.getSegment(i); assertEquals(lastSeg.getSegmentNumber(), seg.getSegmentNumber()); assertEquals(lastSeg.getSegmentStart(), seg.getSegmentStart()); assertEquals(lastSeg.getSegmentEnd(), seg.getSegmentEnd()); assertTrue(lastSeg.getMillisecond() < seg.getMillisecond()); lastSeg = seg; } // try next segment seg = timeline.getSegment(end + 1); assertEquals(segment2.getSegmentNumber(), seg.getSegmentNumber()); assertEquals(segment2.getSegmentStart(), seg.getSegmentStart()); assertEquals(segment2.getSegmentEnd(), seg.getSegmentEnd()); } } ////////////////////////////////////////////////////////////////////////// // test inc methods ////////////////////////////////////////////////////////////////////////// /** * Tests the inc methods on the msTimeline. */ public void testMsInc() { verifyInc(this.msTimeline); } /** * Tests the inc methods on the msTimeline. */ public void testMs2Inc() { verifyInc(this.ms2Timeline); } /** * Tests the inc methods on the Monday through Friday timeline. */ public void testMondayThroughFridayInc() { verifyInc(this.mondayFridayTimeline); } /** * Tests the inc methods on the Fifteen minute timeline. */ public void testFifteenMinInc() { verifyInc(this.fifteenMinTimeline); } /** * Tests the inc methods. * @param timeline the timeline to use for verifications. */ public void verifyInc(SegmentedTimeline timeline) { for (long testCycle = TEST_CYCLE_START; testCycle < TEST_CYCLE_END; testCycle += TEST_CYCLE_INC) { long m = timeline.getSegmentSize(); SegmentedTimeline.Segment segment = timeline.getSegment(testCycle); SegmentedTimeline.Segment seg1 = segment.copy(); for (int i = 0; i < 1000; i++) { // test inc() method SegmentedTimeline.Segment seg2 = seg1.copy(); seg2.inc(); if ((seg1.getSegmentEnd() + 1) != seg2.getSegmentStart()) { // logically consecutive segments non-physically consecutive // (with non-contained time in between) assertTrue(!timeline.containsDomainRange( seg1.getSegmentEnd() + 1, seg2.getSegmentStart() - 1)); assertEquals(0, (seg2.getSegmentStart() - seg1.getSegmentStart()) % m); assertEquals(0, (seg2.getSegmentEnd() - seg1.getSegmentEnd()) % m); assertEquals(0, (seg2.getMillisecond() - seg1.getMillisecond()) % m); } else { // physically consecutive assertEquals(seg1.getSegmentStart() + m, seg2.getSegmentStart()); assertEquals(seg1.getSegmentEnd() + m, seg2.getSegmentEnd()); assertEquals(seg1.getMillisecond() + m, seg2.getMillisecond()); } // test inc(n) method SegmentedTimeline.Segment seg3 = seg1.copy(); SegmentedTimeline.Segment seg4 = seg1.copy(); for (int j = 0; j < i; j++) { seg3.inc(); } seg4.inc(i); assertEquals(seg3.getSegmentStart(), seg4.getSegmentStart()); assertEquals(seg3.getSegmentEnd(), seg4.getSegmentEnd()); assertEquals(seg3.getMillisecond(), seg4.getMillisecond()); // go to another segment to continue test seg1.inc(); } } } ////////////////////////////////////////////////////////////////////////// // main include and excluded segments ////////////////////////////////////////////////////////////////////////// /** * Tests that the msTimeline's included and excluded * segments are being calculated correctly. */ public void testMsIncludedAndExcludedSegments() { verifyIncludedAndExcludedSegments(this.msTimeline, 0); } /** * Tests that the ms2Timeline's included and excluded * segments are being calculated correctly. */ public void testMs2IncludedAndExcludedSegments() { verifyIncludedAndExcludedSegments(this.ms2Timeline, 1); } /** * Tests that the Monday through Friday timeline's included and excluded * segments are being calculated correctly. The test is performed starting * on the first monday after 1/1/2000 and for five years. */ public void testMondayThroughFridayIncludedAndExcludedSegments() { verifyIncludedAndExcludedSegments(this.mondayFridayTimeline, this.monday.getTime().getTime()); } /** * Tests that the Fifteen-Min timeline's included and excluded * segments are being calculated correctly. The test is performed starting * on the first monday after 1/1/2000 and for five years. */ public void testFifteenMinIncludedAndExcludedSegments() { verifyIncludedAndExcludedSegments(this.fifteenMinTimeline, this.monday9am.getTime().getTime()); } /** * Tests that a timeline's included and excluded segments are being * calculated correctly. * * @param timeline the timeline to verify * @param n the first segment number to start verifying */ public void verifyIncludedAndExcludedSegments(SegmentedTimeline timeline, long n) { // clear any exceptions in this timeline timeline.setExceptionSegments(new java.util.ArrayList()); // test some included and excluded segments SegmentedTimeline.Segment segment = timeline.getSegment(n); for (int i = 0; i < 1000; i++) { int d = (i % timeline.getGroupSegmentCount()); if (d < timeline.getSegmentsIncluded()) { // should be an included segment assertTrue(segment.inIncludeSegments()); assertTrue(!segment.inExcludeSegments()); assertTrue(!segment.inExceptionSegments()); } else { // should be an excluded segment assertTrue(!segment.inIncludeSegments()); assertTrue(segment.inExcludeSegments()); assertTrue(!segment.inExceptionSegments()); } segment.inc(); } } ////////////////////////////////////////////////////////////////////////// // test exception segments ////////////////////////////////////////////////////////////////////////// /** * Tests methods related to exceptions methods in the msTimeline. * * @throws ParseException if there is a parsing error. */ public void testMsExceptionSegments() throws ParseException { verifyExceptionSegments(this.msTimeline, MS_EXCEPTIONS, NUMBER_FORMAT); } /** * Tests methods related to exceptions methods in the ms2BaseTimeline. * * @throws ParseException if there is a parsing error. */ public void testMs2BaseTimelineExceptionSegments() throws ParseException { verifyExceptionSegments(this.ms2BaseTimeline, MS2_BASE_TIMELINE_EXCEPTIONS, NUMBER_FORMAT); } /** * Tests methods related to exceptions methods in the mondayFridayTimeline. * * @throws ParseException if there is a parsing error. */ public void testMondayThoughFridayExceptionSegments() throws ParseException { verifyExceptionSegments(this.mondayFridayTimeline, US_HOLIDAYS, DATE_FORMAT); } /** * Tests methods related to exceptions methods in the fifteenMinTimeline. * * @throws ParseException if there is a parsing error. */ public void testFifteenMinExceptionSegments() throws ParseException { verifyExceptionSegments(this.fifteenMinTimeline, FIFTEEN_MIN_EXCEPTIONS, DATE_TIME_FORMAT); } /** * Tests methods related to adding exceptions. * * @param timeline the timeline to verify * @param exceptionString array of Strings that represent the exceptions * @param fmt Format object that can parse the exceptionString strings * * @throws ParseException if there is a parsing error. */ public void verifyExceptionSegments(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException { // fill in the exceptions long[] exception = verifyFillInExceptions(timeline, exceptionString, fmt); int m = exception.length; // verify list of exceptions assertEquals(exception.length, timeline.getExceptionSegments().size()); SegmentedTimeline.Segment lastSegment = timeline.getSegment( exception[m - 1]); for (int i = 0; i < m; i++) { SegmentedTimeline.Segment segment = timeline.getSegment( exception[i]); assertTrue(segment.inExceptionSegments()); // include current exception and last one assertEquals(m - i, timeline.getExceptionSegmentCount( segment.getSegmentStart(), lastSegment.getSegmentEnd())); // exclude current exception and last one assertEquals(Math.max(0, m - i - 2), timeline.getExceptionSegmentCount(exception[i] + 1, exception[m - 1] - 1)); } } ////////////////////////////////////////////////////////////////////////// // test timeline translations ////////////////////////////////////////////////////////////////////////// /** * Tests translations for 1-ms timeline * * @throws ParseException if there is a parsing error. */ public void testMsTranslations() throws ParseException { verifyFillInExceptions(this.msTimeline, MS_EXCEPTIONS, NUMBER_FORMAT); verifyTranslations(this.msTimeline, 0); } /** * Tests translations for the base timeline used for the ms2Timeline * * @throws ParseException if there is a parsing error. */ public void testMs2BaseTimelineTranslations() throws ParseException { verifyFillInExceptions(this.ms2BaseTimeline, MS2_BASE_TIMELINE_EXCEPTIONS, NUMBER_FORMAT); verifyTranslations(this.ms2BaseTimeline, 0); } /** * Tests translations for the Monday through Friday timeline * * @throws ParseException if there is a parsing error. */ public void testMs2Translations() throws ParseException { fillInBaseTimelineExceptions(this.ms2Timeline, MS2_BASE_TIMELINE_EXCEPTIONS, NUMBER_FORMAT); fillInBaseTimelineExclusionsAsExceptions(this.ms2Timeline, 0, 5000); verifyTranslations(this.ms2Timeline, 1); } /** * Tests translations for the Monday through Friday timeline * * @throws ParseException if there is a parsing error. */ public void textMondayThroughFridayTranslations() throws ParseException { verifyFillInExceptions(this.mondayFridayTimeline, US_HOLIDAYS, DATE_FORMAT); verifyTranslations(this.mondayFridayTimeline, this.monday.getTime().getTime()); } /** * Tests translations for the Fifteen Min timeline * * @throws ParseException if there is a parsing error. */ public void testFifteenMinTranslations() throws ParseException { verifyFillInExceptions(this.fifteenMinTimeline, FIFTEEN_MIN_EXCEPTIONS, DATE_TIME_FORMAT); fillInBaseTimelineExceptions(this.fifteenMinTimeline, US_HOLIDAYS, DATE_FORMAT); fillInBaseTimelineExclusionsAsExceptions(this.fifteenMinTimeline, this.monday9am.getTime().getTime(), this.monday9am.getTime().getTime() + FIVE_YEARS); verifyTranslations(this.fifteenMinTimeline, this.monday9am.getTime().getTime()); } /** * Tests translations between timelines. * * @param timeline the timeline to use for verifications. * @param startTest ??. */ public void verifyTranslations(SegmentedTimeline timeline, long startTest) { for (long testCycle = TEST_CYCLE_START; testCycle < TEST_CYCLE_END; testCycle += TEST_CYCLE_INC) { long millisecond = startTest + testCycle * timeline.getSegmentSize(); SegmentedTimeline.Segment segment = timeline.getSegment( millisecond); for (int i = 0; i < 1000; i++) { long translatedValue = timeline.toTimelineValue( segment.getMillisecond()); long newValue = timeline.toMillisecond(translatedValue); if (segment.inExcludeSegments() || segment.inExceptionSegments()) { // the reverse transformed value will be in the start of the // next non-excluded and non-exception segment SegmentedTimeline.Segment tempSegment = segment.copy(); tempSegment.moveIndexToStart(); do { tempSegment.inc(); } while (!tempSegment.inIncludeSegments()); assertEquals(tempSegment.getMillisecond(), newValue); } else { assertEquals(segment.getMillisecond(), newValue); } segment.inc(); } } } ////////////////////////////////////////////////////////////////////////// // test serialization ////////////////////////////////////////////////////////////////////////// /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { verifySerialization(this.msTimeline); verifySerialization(this.ms2Timeline); verifySerialization(this.ms2BaseTimeline); verifySerialization(SegmentedTimeline.newMondayThroughFridayTimeline()); verifySerialization(SegmentedTimeline.newFifteenMinuteTimeline()); } /** * Tests serialization of an instance. * @param a1 The timeline to verify the serialization */ private void verifySerialization(SegmentedTimeline a1) { SegmentedTimeline 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 = (SegmentedTimeline) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(a1, a2); } /** * Adds an array of exceptions to the timeline. The timeline exception list * is first cleared. * @param timeline The timeline where the exceptions will be stored * @param exceptionString The exceptions to load * @param fmt The date formatter to use to parse each exceptions[i] value * @throws ParseException If there is any exception parsing each * exceptions[i] value. * @return An array of Dates[] containing each exception date. */ private long[] verifyFillInExceptions(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException { // make sure there are no exceptions timeline.setExceptionSegments(new java.util.ArrayList()); assertEquals(0, timeline.getExceptionSegments().size()); // add our exceptions and store locally in ArrayList of Longs ArrayList exceptionList = new ArrayList(); for (int i = 0; i < exceptionString.length; i++) { long e; if (fmt instanceof NumberFormat) { e = ((NumberFormat) fmt).parse(exceptionString[i]).longValue(); } else { e = timeline.getTime(((SimpleDateFormat) fmt) .parse(exceptionString[i])); } // only add an exception if it is currently an included segment SegmentedTimeline.Segment segment = timeline.getSegment(e); if (segment.inIncludeSegments()) { timeline.addException(e); exceptionList.add(new Long(e)); assertEquals(exceptionList.size(), timeline.getExceptionSegments().size()); assertTrue(segment.inExceptionSegments()); } } // make array of exceptions long[] exception = new long[exceptionList.size()]; int i = 0; for (Iterator iter = exceptionList.iterator(); iter.hasNext();) { Long l = (Long) iter.next(); exception[i++] = l.longValue(); } return (exception); } /** * Adds an array of exceptions relative to the base timeline. * * @param timeline The timeline where the exceptions will be stored * @param exceptionString The exceptions to load * @param fmt The date formatter to use to parse each exceptions[i] value * @throws ParseException If there is any exception parsing each * exceptions[i] value. */ private void fillInBaseTimelineExceptions(SegmentedTimeline timeline, String[] exceptionString, Format fmt) throws ParseException { SegmentedTimeline baseTimeline = timeline.getBaseTimeline(); for (int i = 0; i < exceptionString.length; i++) { long e; if (fmt instanceof NumberFormat) { e = ((NumberFormat) fmt).parse(exceptionString[i]).longValue(); } else { e = timeline.getTime(((SimpleDateFormat) fmt) .parse(exceptionString[i])); } timeline.addBaseTimelineException(e); // verify all timeline segments included in the // baseTimeline.segment are now exceptions SegmentedTimeline.Segment segment1 = baseTimeline.getSegment(e); for (SegmentedTimeline.Segment segment2 = timeline.getSegment(segment1.getSegmentStart()); segment2.getSegmentStart() <= segment1.getSegmentEnd(); segment2.inc()) { if (!segment2.inExcludeSegments()) { assertTrue(segment2.inExceptionSegments()); } } } } /** * Adds new exceptions to a timeline. The exceptions are the excluded * segments from its base timeline. * * @param timeline the timeline. * @param from the start. * @param to the end. */ private void fillInBaseTimelineExclusionsAsExceptions( SegmentedTimeline timeline, long from, long to) { // add the base timeline exclusions as timeline's esceptions timeline.addBaseTimelineExclusions(from, to); // validate base timeline exclusions added as timeline's esceptions for (SegmentedTimeline.Segment segment1 = timeline.getBaseTimeline() .getSegment(from); segment1.getSegmentStart() <= to; segment1.inc()) { if (segment1.inExcludeSegments()) { // verify all timeline segments included in the // baseTimeline.segment are now exceptions for (SegmentedTimeline.Segment segment2 = timeline.getSegment( segment1.getSegmentStart()); segment2.getSegmentStart() <= segment1.getSegmentEnd(); segment2.inc()) { if (!segment2.inExcludeSegments()) { assertTrue(segment2.inExceptionSegments()); } } } } } /** * Confirm that cloning works. */ public void testCloning() { SegmentedTimeline l1 = new SegmentedTimeline(1000, 5, 2); SegmentedTimeline l2 = null; try { l2 = (SegmentedTimeline) l1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(l1 != l2); assertTrue(l1.getClass() == l2.getClass()); assertTrue(l1.equals(l2)); } /** * Confirm that the equals method can distinguish all the required fields. */ public void testEquals() { SegmentedTimeline l1 = new SegmentedTimeline(1000, 5, 2); SegmentedTimeline l2 = new SegmentedTimeline(1000, 5, 2); assertTrue(l1.equals(l2)); l1 = new SegmentedTimeline(1000, 5, 2); l2 = new SegmentedTimeline(1001, 5, 2); assertFalse(l1.equals(l2)); l1 = new SegmentedTimeline(1000, 5, 2); l2 = new SegmentedTimeline(1000, 4, 2); assertFalse(l1.equals(l2)); l1 = new SegmentedTimeline(1000, 5, 2); l2 = new SegmentedTimeline(1000, 5, 1); assertFalse(l1.equals(l2)); l1 = new SegmentedTimeline(1000, 5, 2); l2 = new SegmentedTimeline(1000, 5, 2); // start time... l1.setStartTime(1234L); assertFalse(l1.equals(l2)); l2.setStartTime(1234L); assertTrue(l1.equals(l2)); } /** * Two objects that are equal are required to return the same hashCode. */ public void testHashCode() { SegmentedTimeline l1 = new SegmentedTimeline(1000, 5, 2); SegmentedTimeline l2 = new SegmentedTimeline(1000, 5, 2); assertTrue(l1.equals(l2)); int h1 = l1.hashCode(); int h2 = l2.hashCode(); assertEquals(h1, h2); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization2() { SegmentedTimeline l1 = new SegmentedTimeline(1000, 5, 2); SegmentedTimeline l2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(l1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); l2 = (SegmentedTimeline) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } boolean b = l1.equals(l2); assertTrue(b); } ////////////////////////////////////////////////////////////////////////// // utility methods ////////////////////////////////////////////////////////////////////////// /** * Tests a basic segmented timeline. */ public void testBasicSegmentedTimeline() { SegmentedTimeline stl = new SegmentedTimeline(10, 2, 3); stl.setStartTime(946684800000L); // 1-Jan-2000 assertFalse(stl.containsDomainValue(946684799999L)); assertTrue(stl.containsDomainValue(946684800000L)); assertTrue(stl.containsDomainValue(946684800019L)); assertFalse(stl.containsDomainValue(946684800020L)); assertFalse(stl.containsDomainValue(946684800049L)); assertTrue(stl.containsDomainValue(946684800050L)); assertTrue(stl.containsDomainValue(946684800069L)); assertFalse(stl.containsDomainValue(946684800070L)); assertFalse(stl.containsDomainValue(946684800099L)); assertTrue(stl.containsDomainValue(946684800100L)); assertEquals(0, stl.toTimelineValue(946684800000L)); assertEquals(19, stl.toTimelineValue(946684800019L)); assertEquals(20, stl.toTimelineValue(946684800020L)); assertEquals(20, stl.toTimelineValue(946684800049L)); assertEquals(20, stl.toTimelineValue(946684800050L)); assertEquals(39, stl.toTimelineValue(946684800069L)); assertEquals(40, stl.toTimelineValue(946684800070L)); assertEquals(40, stl.toTimelineValue(946684800099L)); assertEquals(40, stl.toTimelineValue(946684800100L)); assertEquals(946684800000L, stl.toMillisecond(0)); assertEquals(946684800019L, stl.toMillisecond(19)); assertEquals(946684800050L, stl.toMillisecond(20)); assertEquals(946684800069L, stl.toMillisecond(39)); assertEquals(946684800100L, stl.toMillisecond(40)); } /** * Tests a basic time line with one exception. */ public void testSegmentedTimelineWithException1() { SegmentedTimeline stl = new SegmentedTimeline(10, 2, 3); stl.setStartTime(946684800000L); // 1-Jan-2000 stl.addException(946684800050L); assertFalse(stl.containsDomainValue(946684799999L)); assertTrue(stl.containsDomainValue(946684800000L)); assertTrue(stl.containsDomainValue(946684800019L)); assertFalse(stl.containsDomainValue(946684800020L)); assertFalse(stl.containsDomainValue(946684800049L)); assertFalse(stl.containsDomainValue(946684800050L)); assertFalse(stl.containsDomainValue(946684800059L)); assertTrue(stl.containsDomainValue(946684800060L)); assertTrue(stl.containsDomainValue(946684800069L)); assertFalse(stl.containsDomainValue(946684800070L)); assertFalse(stl.containsDomainValue(946684800099L)); assertTrue(stl.containsDomainValue(946684800100L)); //long v = stl.toTimelineValue(946684800020L); assertEquals(0, stl.toTimelineValue(946684800000L)); assertEquals(19, stl.toTimelineValue(946684800019L)); assertEquals(20, stl.toTimelineValue(946684800020L)); assertEquals(20, stl.toTimelineValue(946684800049L)); assertEquals(20, stl.toTimelineValue(946684800050L)); assertEquals(29, stl.toTimelineValue(946684800069L)); assertEquals(30, stl.toTimelineValue(946684800070L)); assertEquals(30, stl.toTimelineValue(946684800099L)); assertEquals(30, stl.toTimelineValue(946684800100L)); assertEquals(946684800000L, stl.toMillisecond(0)); assertEquals(946684800019L, stl.toMillisecond(19)); assertEquals(946684800060L, stl.toMillisecond(20)); assertEquals(946684800069L, stl.toMillisecond(29)); assertEquals(946684800100L, stl.toMillisecond(30)); } ////////////////////////////////////////////////////////////////////////// // main method only for debug ////////////////////////////////////////////////////////////////////////// /** * Only use to debug JUnit suite. * * @param args ignored. * * @throws Exception if there is some problem. */ public static void main(String[] args) throws Exception { SegmentedTimelineTests test = new SegmentedTimelineTests("Test"); test.setUp(); test.testMondayThoughFridayExceptionSegments(); test.tearDown(); } }
[ { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "access$400", "be_test_function_signature": "(Lorg/jfree/chart/axis/SegmentedTimeline;Lorg/jfree/chart/axis/SegmentedTimeline$Segment;)I", "line_numbers": [ "166" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "binarySearchExceptionSegments", "be_test_function_signature": "(Lorg/jfree/chart/axis/SegmentedTimeline$Segment;)I", "line_numbers": [ "1144", "1145", "1147", "1148", "1149", "1152", "1153", "1156", "1157", "1159", "1160", "1163", "1165", "1166" ], "method_line_rate": 0.2857142857142857 }, { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "containsDomainValue", "be_test_function_signature": "(J)Z", "line_numbers": [ "744", "745" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "firstMondayAfter1900", "be_test_function_signature": "()J", "line_numbers": [ "354", "355", "359", "360", "361", "362", "363", "367" ], "method_line_rate": 0.875 }, { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "getExceptionSegmentCount", "be_test_function_signature": "(JJ)J", "line_numbers": [ "1026", "1027", "1030", "1031", "1032", "1033", "1034", "1036", "1037", "1039", "1041" ], "method_line_rate": 0.5454545454545454 }, { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "getSegment", "be_test_function_signature": "(J)Lorg/jfree/chart/axis/SegmentedTimeline$Segment;", "line_numbers": [ "1056" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "getSegmentSize", "be_test_function_signature": "()J", "line_numbers": [ "518" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "getStartTime", "be_test_function_signature": "()J", "line_numbers": [ "452" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "getTimeFromLong", "be_test_function_signature": "(J)J", "line_numbers": [ "716", "717", "718", "719", "727", "731", "733" ], "method_line_rate": 0.42857142857142855 }, { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "newFifteenMinuteTimeline", "be_test_function_signature": "()Lorg/jfree/chart/axis/SegmentedTimeline;", "line_numbers": [ "403", "405", "407", "408" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "newMondayThroughFridayTimeline", "be_test_function_signature": "()Lorg/jfree/chart/axis/SegmentedTimeline;", "line_numbers": [ "379", "381", "382" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "setBaseTimeline", "be_test_function_signature": "(Lorg/jfree/chart/axis/SegmentedTimeline;)V", "line_numbers": [ "557", "558", "559", "563", "564", "567", "568", "572", "574", "579", "580" ], "method_line_rate": 0.6363636363636364 }, { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "setStartTime", "be_test_function_signature": "(J)V", "line_numbers": [ "442", "443" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "toMillisecond", "be_test_function_signature": "(J)J", "line_numbers": [ "669", "673", "676", "682", "684", "687", "689", "691", "694", "697", "698", "699", "702", "703", "705" ], "method_line_rate": 0.6 }, { "be_test_class_file": "org/jfree/chart/axis/SegmentedTimeline.java", "be_test_class_name": "org.jfree.chart.axis.SegmentedTimeline", "be_test_function_name": "toTimelineValue", "be_test_function_signature": "(J)J", "line_numbers": [ "594", "595", "596", "598", "599", "603", "604", "606", "607", "610", "611", "613", "614", "615", "617", "627", "628", "634", "642" ], "method_line_rate": 0.7368421052631579 } ]
public class BorderArrangementTests extends TestCase
public void testBugX() { RectangleConstraint constraint = new RectangleConstraint( new Range(0.0, 200.0), new Range(0.0, 100.0)); BlockContainer container = new BlockContainer(new BorderArrangement()); BufferedImage image = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); container.add(new EmptyBlock(10.0, 6.0), RectangleEdge.LEFT); container.add(new EmptyBlock(20.0, 6.0), RectangleEdge.RIGHT); container.add(new EmptyBlock(30.0, 6.0)); Size2D size = container.arrange(g2, constraint); assertEquals(60.0, size.width, EPSILON); assertEquals(6.0, size.height, EPSILON); container.clear(); container.add(new EmptyBlock(10.0, 6.0), RectangleEdge.LEFT); container.add(new EmptyBlock(20.0, 6.0), RectangleEdge.RIGHT); container.add(new EmptyBlock(300.0, 6.0)); size = container.arrange(g2, constraint); assertEquals(200.0, size.width, EPSILON); assertEquals(6.0, size.height, EPSILON); }
// // Abstract Java Tested Class // package org.jfree.chart.block; // // import java.awt.Graphics2D; // import java.awt.geom.Rectangle2D; // import java.io.Serializable; // import org.jfree.chart.util.ObjectUtilities; // import org.jfree.chart.util.RectangleEdge; // import org.jfree.chart.util.Size2D; // import org.jfree.data.Range; // // // // public class BorderArrangement implements Arrangement, Serializable { // private static final long serialVersionUID = 506071142274883745L; // private Block centerBlock; // private Block topBlock; // private Block bottomBlock; // private Block leftBlock; // private Block rightBlock; // // public BorderArrangement(); // public void add(Block block, Object key); // public Size2D arrange(BlockContainer container, // Graphics2D g2, // RectangleConstraint constraint); // protected Size2D arrangeNN(BlockContainer container, Graphics2D g2); // protected Size2D arrangeFR(BlockContainer container, Graphics2D g2, // RectangleConstraint constraint); // protected Size2D arrangeFN(BlockContainer container, Graphics2D g2, // double width); // protected Size2D arrangeRR(BlockContainer container, // Range widthRange, Range heightRange, // Graphics2D g2); // protected Size2D arrangeFF(BlockContainer container, Graphics2D g2, // RectangleConstraint constraint); // public void clear(); // public boolean equals(Object obj); // } // // // Abstract Java Test Class // package org.jfree.chart.block.junit; // // import java.awt.Graphics2D; // 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 junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.chart.block.Block; // import org.jfree.chart.block.BlockContainer; // import org.jfree.chart.block.BorderArrangement; // import org.jfree.chart.block.EmptyBlock; // import org.jfree.chart.block.LengthConstraintType; // import org.jfree.chart.block.RectangleConstraint; // import org.jfree.chart.util.RectangleEdge; // import org.jfree.chart.util.Size2D; // import org.jfree.data.Range; // // // // public class BorderArrangementTests extends TestCase { // private static final double EPSILON = 0.0000000001; // // public static Test suite(); // public BorderArrangementTests(String name); // public void testEquals(); // public void testCloning(); // public void testSerialization(); // public void testSizing(); // public void testSizingWithWidthConstraint(); // public void testBugX(); // } // You are a professional Java test case writer, please create a test case named `testBugX` for the `BorderArrangement` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * This test is for a particular bug that arose just prior to the release * of JFreeChart 1.0.10. A BorderArrangement with LEFT, CENTRE and RIGHT * blocks that is too wide, by default, for the available space, wasn't * shrinking the centre block as expected. */
tests/org/jfree/chart/block/junit/BorderArrangementTests.java
package org.jfree.chart.block; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.RectangleEdge; import org.jfree.chart.util.Size2D; import org.jfree.data.Range;
public BorderArrangement(); public void add(Block block, Object key); public Size2D arrange(BlockContainer container, Graphics2D g2, RectangleConstraint constraint); protected Size2D arrangeNN(BlockContainer container, Graphics2D g2); protected Size2D arrangeFR(BlockContainer container, Graphics2D g2, RectangleConstraint constraint); protected Size2D arrangeFN(BlockContainer container, Graphics2D g2, double width); protected Size2D arrangeRR(BlockContainer container, Range widthRange, Range heightRange, Graphics2D g2); protected Size2D arrangeFF(BlockContainer container, Graphics2D g2, RectangleConstraint constraint); public void clear(); public boolean equals(Object obj);
844
testBugX
```java // Abstract Java Tested Class package org.jfree.chart.block; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.RectangleEdge; import org.jfree.chart.util.Size2D; import org.jfree.data.Range; public class BorderArrangement implements Arrangement, Serializable { private static final long serialVersionUID = 506071142274883745L; private Block centerBlock; private Block topBlock; private Block bottomBlock; private Block leftBlock; private Block rightBlock; public BorderArrangement(); public void add(Block block, Object key); public Size2D arrange(BlockContainer container, Graphics2D g2, RectangleConstraint constraint); protected Size2D arrangeNN(BlockContainer container, Graphics2D g2); protected Size2D arrangeFR(BlockContainer container, Graphics2D g2, RectangleConstraint constraint); protected Size2D arrangeFN(BlockContainer container, Graphics2D g2, double width); protected Size2D arrangeRR(BlockContainer container, Range widthRange, Range heightRange, Graphics2D g2); protected Size2D arrangeFF(BlockContainer container, Graphics2D g2, RectangleConstraint constraint); public void clear(); public boolean equals(Object obj); } // Abstract Java Test Class package org.jfree.chart.block.junit; import java.awt.Graphics2D; 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 junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.block.Block; import org.jfree.chart.block.BlockContainer; import org.jfree.chart.block.BorderArrangement; import org.jfree.chart.block.EmptyBlock; import org.jfree.chart.block.LengthConstraintType; import org.jfree.chart.block.RectangleConstraint; import org.jfree.chart.util.RectangleEdge; import org.jfree.chart.util.Size2D; import org.jfree.data.Range; public class BorderArrangementTests extends TestCase { private static final double EPSILON = 0.0000000001; public static Test suite(); public BorderArrangementTests(String name); public void testEquals(); public void testCloning(); public void testSerialization(); public void testSizing(); public void testSizingWithWidthConstraint(); public void testBugX(); } ``` You are a professional Java test case writer, please create a test case named `testBugX` for the `BorderArrangement` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * This test is for a particular bug that arose just prior to the release * of JFreeChart 1.0.10. A BorderArrangement with LEFT, CENTRE and RIGHT * blocks that is too wide, by default, for the available space, wasn't * shrinking the centre block as expected. */
820
// // Abstract Java Tested Class // package org.jfree.chart.block; // // import java.awt.Graphics2D; // import java.awt.geom.Rectangle2D; // import java.io.Serializable; // import org.jfree.chart.util.ObjectUtilities; // import org.jfree.chart.util.RectangleEdge; // import org.jfree.chart.util.Size2D; // import org.jfree.data.Range; // // // // public class BorderArrangement implements Arrangement, Serializable { // private static final long serialVersionUID = 506071142274883745L; // private Block centerBlock; // private Block topBlock; // private Block bottomBlock; // private Block leftBlock; // private Block rightBlock; // // public BorderArrangement(); // public void add(Block block, Object key); // public Size2D arrange(BlockContainer container, // Graphics2D g2, // RectangleConstraint constraint); // protected Size2D arrangeNN(BlockContainer container, Graphics2D g2); // protected Size2D arrangeFR(BlockContainer container, Graphics2D g2, // RectangleConstraint constraint); // protected Size2D arrangeFN(BlockContainer container, Graphics2D g2, // double width); // protected Size2D arrangeRR(BlockContainer container, // Range widthRange, Range heightRange, // Graphics2D g2); // protected Size2D arrangeFF(BlockContainer container, Graphics2D g2, // RectangleConstraint constraint); // public void clear(); // public boolean equals(Object obj); // } // // // Abstract Java Test Class // package org.jfree.chart.block.junit; // // import java.awt.Graphics2D; // 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 junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.chart.block.Block; // import org.jfree.chart.block.BlockContainer; // import org.jfree.chart.block.BorderArrangement; // import org.jfree.chart.block.EmptyBlock; // import org.jfree.chart.block.LengthConstraintType; // import org.jfree.chart.block.RectangleConstraint; // import org.jfree.chart.util.RectangleEdge; // import org.jfree.chart.util.Size2D; // import org.jfree.data.Range; // // // // public class BorderArrangementTests extends TestCase { // private static final double EPSILON = 0.0000000001; // // public static Test suite(); // public BorderArrangementTests(String name); // public void testEquals(); // public void testCloning(); // public void testSerialization(); // public void testSizing(); // public void testSizingWithWidthConstraint(); // public void testBugX(); // } // You are a professional Java test case writer, please create a test case named `testBugX` for the `BorderArrangement` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * This test is for a particular bug that arose just prior to the release * of JFreeChart 1.0.10. A BorderArrangement with LEFT, CENTRE and RIGHT * blocks that is too wide, by default, for the available space, wasn't * shrinking the centre block as expected. */ public void testBugX() {
/** * This test is for a particular bug that arose just prior to the release * of JFreeChart 1.0.10. A BorderArrangement with LEFT, CENTRE and RIGHT * blocks that is too wide, by default, for the available space, wasn't * shrinking the centre block as expected. */
1
org.jfree.chart.block.BorderArrangement
tests
```java // Abstract Java Tested Class package org.jfree.chart.block; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.RectangleEdge; import org.jfree.chart.util.Size2D; import org.jfree.data.Range; public class BorderArrangement implements Arrangement, Serializable { private static final long serialVersionUID = 506071142274883745L; private Block centerBlock; private Block topBlock; private Block bottomBlock; private Block leftBlock; private Block rightBlock; public BorderArrangement(); public void add(Block block, Object key); public Size2D arrange(BlockContainer container, Graphics2D g2, RectangleConstraint constraint); protected Size2D arrangeNN(BlockContainer container, Graphics2D g2); protected Size2D arrangeFR(BlockContainer container, Graphics2D g2, RectangleConstraint constraint); protected Size2D arrangeFN(BlockContainer container, Graphics2D g2, double width); protected Size2D arrangeRR(BlockContainer container, Range widthRange, Range heightRange, Graphics2D g2); protected Size2D arrangeFF(BlockContainer container, Graphics2D g2, RectangleConstraint constraint); public void clear(); public boolean equals(Object obj); } // Abstract Java Test Class package org.jfree.chart.block.junit; import java.awt.Graphics2D; 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 junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.block.Block; import org.jfree.chart.block.BlockContainer; import org.jfree.chart.block.BorderArrangement; import org.jfree.chart.block.EmptyBlock; import org.jfree.chart.block.LengthConstraintType; import org.jfree.chart.block.RectangleConstraint; import org.jfree.chart.util.RectangleEdge; import org.jfree.chart.util.Size2D; import org.jfree.data.Range; public class BorderArrangementTests extends TestCase { private static final double EPSILON = 0.0000000001; public static Test suite(); public BorderArrangementTests(String name); public void testEquals(); public void testCloning(); public void testSerialization(); public void testSizing(); public void testSizingWithWidthConstraint(); public void testBugX(); } ``` You are a professional Java test case writer, please create a test case named `testBugX` for the `BorderArrangement` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * This test is for a particular bug that arose just prior to the release * of JFreeChart 1.0.10. A BorderArrangement with LEFT, CENTRE and RIGHT * blocks that is too wide, by default, for the available space, wasn't * shrinking the centre block as expected. */ public void testBugX() { ```
public class BorderArrangement implements Arrangement, Serializable
package org.jfree.chart.block.junit; import java.awt.Graphics2D; 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 junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.block.Block; import org.jfree.chart.block.BlockContainer; import org.jfree.chart.block.BorderArrangement; import org.jfree.chart.block.EmptyBlock; import org.jfree.chart.block.LengthConstraintType; import org.jfree.chart.block.RectangleConstraint; import org.jfree.chart.util.RectangleEdge; import org.jfree.chart.util.Size2D; import org.jfree.data.Range;
public static Test suite(); public BorderArrangementTests(String name); public void testEquals(); public void testCloning(); public void testSerialization(); public void testSizing(); public void testSizingWithWidthConstraint(); public void testBugX();
72b6594c4593f75ccd4d5c46d73f2232da6bc4594a9d582f3942244775232add
[ "org.jfree.chart.block.junit.BorderArrangementTests::testBugX" ]
private static final long serialVersionUID = 506071142274883745L; private Block centerBlock; private Block topBlock; private Block bottomBlock; private Block leftBlock; private Block rightBlock;
public void testBugX()
private static final double EPSILON = 0.0000000001;
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.] * * --------------------------- * BorderArrangementTests.java * --------------------------- * (C) Copyright 2004-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 22-Oct-2004 : Version 1 (DG); * 20-Jun-2007 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.block.junit; import java.awt.Graphics2D; 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 junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.block.Block; import org.jfree.chart.block.BlockContainer; import org.jfree.chart.block.BorderArrangement; import org.jfree.chart.block.EmptyBlock; import org.jfree.chart.block.LengthConstraintType; import org.jfree.chart.block.RectangleConstraint; import org.jfree.chart.util.RectangleEdge; import org.jfree.chart.util.Size2D; import org.jfree.data.Range; /** * Tests for the {@link BorderArrangement} class. */ public class BorderArrangementTests extends TestCase { private static final double EPSILON = 0.0000000001; /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(BorderArrangementTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public BorderArrangementTests(String name) { super(name); } /** * Confirm that the equals() method can distinguish all the required fields. */ public void testEquals() { BorderArrangement b1 = new BorderArrangement(); BorderArrangement b2 = new BorderArrangement(); assertTrue(b1.equals(b2)); assertTrue(b2.equals(b1)); b1.add(new EmptyBlock(99.0, 99.0), null); assertFalse(b1.equals(b2)); b2.add(new EmptyBlock(99.0, 99.0), null); assertTrue(b1.equals(b2)); b1.add(new EmptyBlock(1.0, 1.0), RectangleEdge.LEFT); assertFalse(b1.equals(b2)); b2.add(new EmptyBlock(1.0, 1.0), RectangleEdge.LEFT); assertTrue(b1.equals(b2)); b1.add(new EmptyBlock(2.0, 2.0), RectangleEdge.RIGHT); assertFalse(b1.equals(b2)); b2.add(new EmptyBlock(2.0, 2.0), RectangleEdge.RIGHT); assertTrue(b1.equals(b2)); b1.add(new EmptyBlock(3.0, 3.0), RectangleEdge.TOP); assertFalse(b1.equals(b2)); b2.add(new EmptyBlock(3.0, 3.0), RectangleEdge.TOP); assertTrue(b1.equals(b2)); b1.add(new EmptyBlock(4.0, 4.0), RectangleEdge.BOTTOM); assertFalse(b1.equals(b2)); b2.add(new EmptyBlock(4.0, 4.0), RectangleEdge.BOTTOM); assertTrue(b1.equals(b2)); } /** * Immutable - cloning is not necessary. */ public void testCloning() { BorderArrangement b1 = new BorderArrangement(); assertFalse(b1 instanceof Cloneable); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { BorderArrangement b1 = new BorderArrangement(); BorderArrangement b2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(b1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); b2 = (BorderArrangement) in.readObject(); in.close(); } catch (Exception e) { fail(e.toString()); } assertEquals(b1, b2); } /** * Run some checks on sizing. */ public void testSizing() { BlockContainer container = new BlockContainer(new BorderArrangement()); BufferedImage image = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); // TBLRC // 00000 - no items Size2D size = container.arrange(g2); assertEquals(0.0, size.width, EPSILON); assertEquals(0.0, size.height, EPSILON); // TBLRC // 00001 - center item only container.add(new EmptyBlock(123.4, 567.8)); size = container.arrange(g2); assertEquals(123.4, size.width, EPSILON); assertEquals(567.8, size.height, EPSILON); // TBLRC // 00010 - right item only container.clear(); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.RIGHT); size = container.arrange(g2); assertEquals(12.3, size.width, EPSILON); assertEquals(45.6, size.height, EPSILON); // TBLRC // 00011 - right and center items container.clear(); container.add(new EmptyBlock(10.0, 20.0)); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.RIGHT); size = container.arrange(g2); assertEquals(22.3, size.width, EPSILON); assertEquals(45.6, size.height, EPSILON); // try case where right item is shorter than center item container.clear(); Block rb = new EmptyBlock(12.3, 15.6); container.add(new EmptyBlock(10.0, 20.0)); container.add(rb, RectangleEdge.RIGHT); size = container.arrange(g2); assertEquals(22.3, size.width, EPSILON); assertEquals(20.0, size.height, EPSILON); assertEquals(20.0, rb.getBounds().getHeight(), EPSILON); // TBLRC // 00100 - left item only container.clear(); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.LEFT); size = container.arrange(g2); assertEquals(12.3, size.width, EPSILON); assertEquals(45.6, size.height, EPSILON); // TBLRC // 00101 - left and center items container.clear(); container.add(new EmptyBlock(10.0, 20.0)); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.LEFT); size = container.arrange(g2); assertEquals(22.3, size.width, EPSILON); assertEquals(45.6, size.height, EPSILON); // try case where left item is shorter than center item container.clear(); Block lb = new EmptyBlock(12.3, 15.6); container.add(new EmptyBlock(10.0, 20.0)); container.add(lb, RectangleEdge.LEFT); size = container.arrange(g2); assertEquals(22.3, size.width, EPSILON); assertEquals(20.0, size.height, EPSILON); assertEquals(20.0, lb.getBounds().getHeight(), EPSILON); // TBLRC // 00110 - left and right items container.clear(); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.RIGHT); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.LEFT); size = container.arrange(g2); assertEquals(22.3, size.width, EPSILON); assertEquals(45.6, size.height, EPSILON); // TBLRC // 00111 - left, right and center items container.clear(); container.add(new EmptyBlock(10.0, 20.0)); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.LEFT); container.add(new EmptyBlock(5.4, 3.2), RectangleEdge.RIGHT); size = container.arrange(g2); assertEquals(27.7, size.width, EPSILON); assertEquals(45.6, size.height, EPSILON); // TBLRC // 01000 - bottom item only container.clear(); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM); size = container.arrange(g2); assertEquals(12.3, size.width, EPSILON); assertEquals(45.6, size.height, EPSILON); // TBLRC // 01001 - bottom and center only container.clear(); container.add(new EmptyBlock(10.0, 20.0)); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM); size = container.arrange(g2); assertEquals(12.3, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 01010 - bottom and right only container.clear(); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.RIGHT); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM); size = container.arrange(g2); assertEquals(12.3, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 01011 - bottom, right and center container.clear(); container.add(new EmptyBlock(21.0, 12.3)); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.RIGHT); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM); size = container.arrange(g2); assertEquals(31.0, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 01100 container.clear(); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.LEFT); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM); size = container.arrange(g2); assertEquals(12.3, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 01101 - bottom, left and center container.clear(); container.add(new EmptyBlock(21.0, 12.3)); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.LEFT); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM); size = container.arrange(g2); assertEquals(31.0, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 01110 - bottom. left and right container.clear(); container.add(new EmptyBlock(21.0, 12.3), RectangleEdge.RIGHT); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.LEFT); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM); size = container.arrange(g2); assertEquals(31.0, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 01111 container.clear(); container.add(new EmptyBlock(3.0, 4.0), RectangleEdge.BOTTOM); container.add(new EmptyBlock(5.0, 6.0), RectangleEdge.LEFT); container.add(new EmptyBlock(7.0, 8.0), RectangleEdge.RIGHT); container.add(new EmptyBlock(9.0, 10.0)); size = container.arrange(g2); assertEquals(21.0, size.width, EPSILON); assertEquals(14.0, size.height, EPSILON); // TBLRC // 10000 - top item only container.clear(); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.TOP); size = container.arrange(g2); assertEquals(12.3, size.width, EPSILON); assertEquals(45.6, size.height, EPSILON); // TBLRC // 10001 - top and center only container.clear(); container.add(new EmptyBlock(10.0, 20.0)); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.TOP); size = container.arrange(g2); assertEquals(12.3, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 10010 - right and top only container.clear(); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.RIGHT); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.TOP); size = container.arrange(g2); assertEquals(12.3, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 10011 - top, right and center container.clear(); container.add(new EmptyBlock(21.0, 12.3)); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.TOP); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.RIGHT); size = container.arrange(g2); assertEquals(33.3, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 10100 - top and left only container.clear(); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.LEFT); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.TOP); size = container.arrange(g2); assertEquals(12.3, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 10101 - top, left and center container.clear(); container.add(new EmptyBlock(21.0, 12.3)); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.TOP); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.LEFT); size = container.arrange(g2); assertEquals(33.3, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 10110 - top, left and right container.clear(); container.add(new EmptyBlock(21.0, 12.3), RectangleEdge.RIGHT); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.TOP); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.LEFT); size = container.arrange(g2); assertEquals(33.3, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 10111 container.clear(); container.add(new EmptyBlock(1.0, 2.0), RectangleEdge.TOP); container.add(new EmptyBlock(5.0, 6.0), RectangleEdge.LEFT); container.add(new EmptyBlock(7.0, 8.0), RectangleEdge.RIGHT); container.add(new EmptyBlock(9.0, 10.0)); size = container.arrange(g2); assertEquals(21.0, size.width, EPSILON); assertEquals(12.0, size.height, EPSILON); // TBLRC // 11000 - top and bottom only container.clear(); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.TOP); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM); size = container.arrange(g2); assertEquals(12.3, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 11001 container.clear(); container.add(new EmptyBlock(21.0, 12.3)); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.TOP); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM); size = container.arrange(g2); assertEquals(21.0, size.width, EPSILON); assertEquals(77.9, size.height, EPSILON); // TBLRC // 11010 - top, bottom and right container.clear(); container.add(new EmptyBlock(21.0, 12.3), RectangleEdge.RIGHT); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.TOP); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM); size = container.arrange(g2); assertEquals(21.0, size.width, EPSILON); assertEquals(77.9, size.height, EPSILON); // TBLRC // 11011 container.clear(); container.add(new EmptyBlock(1.0, 2.0), RectangleEdge.TOP); container.add(new EmptyBlock(3.0, 4.0), RectangleEdge.BOTTOM); container.add(new EmptyBlock(7.0, 8.0), RectangleEdge.RIGHT); container.add(new EmptyBlock(9.0, 10.0)); size = container.arrange(g2); assertEquals(16.0, size.width, EPSILON); assertEquals(16.0, size.height, EPSILON); // TBLRC // 11100 container.clear(); container.add(new EmptyBlock(21.0, 12.3), RectangleEdge.LEFT); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.TOP); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM); size = container.arrange(g2); assertEquals(21.0, size.width, EPSILON); assertEquals(77.9, size.height, EPSILON); // TBLRC // 11101 container.clear(); container.add(new EmptyBlock(1.0, 2.0), RectangleEdge.TOP); container.add(new EmptyBlock(3.0, 4.0), RectangleEdge.BOTTOM); container.add(new EmptyBlock(5.0, 6.0), RectangleEdge.LEFT); container.add(new EmptyBlock(9.0, 10.0)); size = container.arrange(g2); assertEquals(14.0, size.width, EPSILON); assertEquals(16.0, size.height, EPSILON); // TBLRC // 11110 container.clear(); container.add(new EmptyBlock(1.0, 2.0), RectangleEdge.TOP); container.add(new EmptyBlock(3.0, 4.0), RectangleEdge.BOTTOM); container.add(new EmptyBlock(5.0, 6.0), RectangleEdge.LEFT); container.add(new EmptyBlock(7.0, 8.0), RectangleEdge.RIGHT); size = container.arrange(g2); assertEquals(12.0, size.width, EPSILON); assertEquals(14.0, size.height, EPSILON); // TBLRC // 11111 - all container.clear(); container.add(new EmptyBlock(1.0, 2.0), RectangleEdge.TOP); container.add(new EmptyBlock(3.0, 4.0), RectangleEdge.BOTTOM); container.add(new EmptyBlock(5.0, 6.0), RectangleEdge.LEFT); container.add(new EmptyBlock(7.0, 8.0), RectangleEdge.RIGHT); container.add(new EmptyBlock(9.0, 10.0)); size = container.arrange(g2); assertEquals(21.0, size.width, EPSILON); assertEquals(16.0, size.height, EPSILON); } /** * Run some checks on sizing when there is a fixed width constraint. */ public void testSizingWithWidthConstraint() { RectangleConstraint constraint = new RectangleConstraint( 10.0, new Range(10.0, 10.0), LengthConstraintType.FIXED, 0.0, new Range(0.0, 0.0), LengthConstraintType.NONE); BlockContainer container = new BlockContainer(new BorderArrangement()); BufferedImage image = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); // TBLRC // 00001 - center item only container.add(new EmptyBlock(5.0, 6.0)); Size2D size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(6.0, size.height, EPSILON); container.clear(); container.add(new EmptyBlock(15.0, 16.0)); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(16.0, size.height, EPSILON); // TBLRC // 00010 - right item only container.clear(); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.RIGHT); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(45.6, size.height, EPSILON); // TBLRC // 00011 - right and center items container.clear(); container.add(new EmptyBlock(7.0, 20.0)); container.add(new EmptyBlock(8.0, 45.6), RectangleEdge.RIGHT); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(45.6, size.height, EPSILON); // TBLRC // 00100 - left item only container.clear(); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.LEFT); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(45.6, size.height, EPSILON); // TBLRC // 00101 - left and center items container.clear(); container.add(new EmptyBlock(10.0, 20.0)); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.LEFT); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(45.6, size.height, EPSILON); // TBLRC // 00110 - left and right items container.clear(); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.RIGHT); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.LEFT); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(45.6, size.height, EPSILON); // TBLRC // 00111 - left, right and center items container.clear(); container.add(new EmptyBlock(10.0, 20.0)); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.LEFT); container.add(new EmptyBlock(5.4, 3.2), RectangleEdge.RIGHT); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(45.6, size.height, EPSILON); // TBLRC // 01000 - bottom item only container.clear(); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(45.6, size.height, EPSILON); // TBLRC // 01001 - bottom and center only container.clear(); container.add(new EmptyBlock(10.0, 20.0)); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 01010 - bottom and right only container.clear(); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.RIGHT); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 01011 - bottom, right and center container.clear(); container.add(new EmptyBlock(21.0, 12.3)); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.RIGHT); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 01100 container.clear(); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.LEFT); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 01101 - bottom, left and center container.clear(); container.add(new EmptyBlock(21.0, 12.3)); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.LEFT); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 01110 - bottom. left and right container.clear(); container.add(new EmptyBlock(21.0, 12.3), RectangleEdge.RIGHT); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.LEFT); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 01111 container.clear(); container.add(new EmptyBlock(3.0, 4.0), RectangleEdge.BOTTOM); container.add(new EmptyBlock(5.0, 6.0), RectangleEdge.LEFT); container.add(new EmptyBlock(7.0, 8.0), RectangleEdge.RIGHT); container.add(new EmptyBlock(9.0, 10.0)); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(14.0, size.height, EPSILON); // TBLRC // 10000 - top item only container.clear(); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.TOP); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(45.6, size.height, EPSILON); // TBLRC // 10001 - top and center only container.clear(); container.add(new EmptyBlock(10.0, 20.0)); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.TOP); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 10010 - right and top only container.clear(); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.RIGHT); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.TOP); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 10011 - top, right and center container.clear(); container.add(new EmptyBlock(21.0, 12.3)); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.TOP); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.RIGHT); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 10100 - top and left only container.clear(); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.LEFT); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.TOP); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 10101 - top, left and center container.clear(); container.add(new EmptyBlock(21.0, 12.3)); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.TOP); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.LEFT); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 10110 - top, left and right container.clear(); container.add(new EmptyBlock(21.0, 12.3), RectangleEdge.RIGHT); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.TOP); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.LEFT); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 10111 container.clear(); container.add(new EmptyBlock(1.0, 2.0), RectangleEdge.TOP); container.add(new EmptyBlock(5.0, 6.0), RectangleEdge.LEFT); container.add(new EmptyBlock(7.0, 8.0), RectangleEdge.RIGHT); container.add(new EmptyBlock(9.0, 10.0)); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(12.0, size.height, EPSILON); // TBLRC // 11000 - top and bottom only container.clear(); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.TOP); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(65.6, size.height, EPSILON); // TBLRC // 11001 container.clear(); container.add(new EmptyBlock(21.0, 12.3)); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.TOP); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(77.9, size.height, EPSILON); // TBLRC // 11010 - top, bottom and right container.clear(); container.add(new EmptyBlock(21.0, 12.3), RectangleEdge.RIGHT); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.TOP); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(77.9, size.height, EPSILON); // TBLRC // 11011 container.clear(); container.add(new EmptyBlock(1.0, 2.0), RectangleEdge.TOP); container.add(new EmptyBlock(3.0, 4.0), RectangleEdge.BOTTOM); container.add(new EmptyBlock(7.0, 8.0), RectangleEdge.RIGHT); container.add(new EmptyBlock(9.0, 10.0)); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(16.0, size.height, EPSILON); // TBLRC // 11100 container.clear(); container.add(new EmptyBlock(21.0, 12.3), RectangleEdge.LEFT); container.add(new EmptyBlock(10.0, 20.0), RectangleEdge.TOP); container.add(new EmptyBlock(12.3, 45.6), RectangleEdge.BOTTOM); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(77.9, size.height, EPSILON); // TBLRC // 11101 container.clear(); container.add(new EmptyBlock(1.0, 2.0), RectangleEdge.TOP); container.add(new EmptyBlock(3.0, 4.0), RectangleEdge.BOTTOM); container.add(new EmptyBlock(5.0, 6.0), RectangleEdge.LEFT); container.add(new EmptyBlock(9.0, 10.0)); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(16.0, size.height, EPSILON); // TBLRC // 11110 container.clear(); container.add(new EmptyBlock(1.0, 2.0), RectangleEdge.TOP); container.add(new EmptyBlock(3.0, 4.0), RectangleEdge.BOTTOM); container.add(new EmptyBlock(5.0, 6.0), RectangleEdge.LEFT); container.add(new EmptyBlock(7.0, 8.0), RectangleEdge.RIGHT); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(14.0, size.height, EPSILON); // TBLRC // 11111 - all container.clear(); container.add(new EmptyBlock(1.0, 2.0), RectangleEdge.TOP); container.add(new EmptyBlock(3.0, 4.0), RectangleEdge.BOTTOM); container.add(new EmptyBlock(5.0, 6.0), RectangleEdge.LEFT); container.add(new EmptyBlock(7.0, 8.0), RectangleEdge.RIGHT); container.add(new EmptyBlock(9.0, 10.0)); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(16.0, size.height, EPSILON); // TBLRC // 00000 - no items container.clear(); size = container.arrange(g2, constraint); assertEquals(10.0, size.width, EPSILON); assertEquals(0.0, size.height, EPSILON); } /** * This test is for a particular bug that arose just prior to the release * of JFreeChart 1.0.10. A BorderArrangement with LEFT, CENTRE and RIGHT * blocks that is too wide, by default, for the available space, wasn't * shrinking the centre block as expected. */ public void testBugX() { RectangleConstraint constraint = new RectangleConstraint( new Range(0.0, 200.0), new Range(0.0, 100.0)); BlockContainer container = new BlockContainer(new BorderArrangement()); BufferedImage image = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); container.add(new EmptyBlock(10.0, 6.0), RectangleEdge.LEFT); container.add(new EmptyBlock(20.0, 6.0), RectangleEdge.RIGHT); container.add(new EmptyBlock(30.0, 6.0)); Size2D size = container.arrange(g2, constraint); assertEquals(60.0, size.width, EPSILON); assertEquals(6.0, size.height, EPSILON); container.clear(); container.add(new EmptyBlock(10.0, 6.0), RectangleEdge.LEFT); container.add(new EmptyBlock(20.0, 6.0), RectangleEdge.RIGHT); container.add(new EmptyBlock(300.0, 6.0)); size = container.arrange(g2, constraint); assertEquals(200.0, size.width, EPSILON); assertEquals(6.0, size.height, EPSILON); } }
[ { "be_test_class_file": "org/jfree/chart/block/BorderArrangement.java", "be_test_class_name": "org.jfree.chart.block.BorderArrangement", "be_test_function_name": "add", "be_test_function_signature": "(Lorg/jfree/chart/block/Block;Ljava/lang/Object;)V", "line_numbers": [ "98", "99", "102", "103", "104", "106", "107", "109", "110", "112", "113", "116" ], "method_line_rate": 0.8333333333333334 }, { "be_test_class_file": "org/jfree/chart/block/BorderArrangement.java", "be_test_class_name": "org.jfree.chart.block.BorderArrangement", "be_test_function_name": "arrange", "be_test_function_signature": "(Lorg/jfree/chart/block/BlockContainer;Ljava/awt/Graphics2D;Lorg/jfree/chart/block/RectangleConstraint;)Lorg/jfree/chart/util/Size2D;", "line_numbers": [ "131", "133", "134", "135", "136", "137", "138", "140", "141", "143", "144", "147", "148", "149", "151", "152", "154", "155", "158", "159", "160", "162", "163", "165", "166", "170" ], "method_line_rate": 0.46153846153846156 }, { "be_test_class_file": "org/jfree/chart/block/BorderArrangement.java", "be_test_class_name": "org.jfree.chart.block.BorderArrangement", "be_test_function_name": "arrangeRR", "be_test_function_signature": "(Lorg/jfree/chart/block/BlockContainer;Lorg/jfree/data/Range;Lorg/jfree/data/Range;Ljava/awt/Graphics2D;)Lorg/jfree/chart/util/Size2D;", "line_numbers": [ "340", "341", "342", "343", "345", "346", "347", "349", "350", "351", "353", "354", "355", "357", "358", "359", "361", "362", "363", "365", "366", "367", "369", "370", "371", "374", "375", "376", "377", "378", "383", "384", "385", "387", "388", "389", "390", "393", "394", "397", "398", "401", "402", "406", "407", "410" ], "method_line_rate": 0.7608695652173914 }, { "be_test_class_file": "org/jfree/chart/block/BorderArrangement.java", "be_test_class_name": "org.jfree.chart.block.BorderArrangement", "be_test_function_name": "clear", "be_test_function_signature": "()V", "line_numbers": [ "495", "496", "497", "498", "499", "500" ], "method_line_rate": 1 } ]
public class SoundexTest extends StringEncoderAbstractTest<Soundex>
@Test public void testHWRuleEx3() throws EncoderException { Assert.assertEquals("S460", this.getStringEncoder().encode("Sgler")); Assert.assertEquals("S460", this.getStringEncoder().encode("Swhgler")); // Also S460: this.checkEncodingVariations("S460", new String[]{ "SAILOR", "SALYER", "SAYLOR", "SCHALLER", "SCHELLER", "SCHILLER", "SCHOOLER", "SCHULER", "SCHUYLER", "SEILER", "SEYLER", "SHOLAR", "SHULER", "SILAR", "SILER", "SILLER"}); }
// // Abstract Java Tested Class // package org.apache.commons.codec.language; // // import org.apache.commons.codec.EncoderException; // import org.apache.commons.codec.StringEncoder; // // // // public class Soundex implements StringEncoder { // public static final String US_ENGLISH_MAPPING_STRING = "0123012#02245501262301#202"; // private static final char[] US_ENGLISH_MAPPING = US_ENGLISH_MAPPING_STRING.toCharArray(); // public static final Soundex US_ENGLISH = new Soundex(); // @Deprecated // private int maxLength = 4; // private final char[] soundexMapping; // // public Soundex(); // public Soundex(final char[] mapping); // public Soundex(final String mapping); // public int difference(final String s1, final String s2) throws EncoderException; // @Override // public Object encode(final Object obj) throws EncoderException; // @Override // public String encode(final String str); // @Deprecated // public int getMaxLength(); // private char[] getSoundexMapping(); // private char map(final char ch); // @Deprecated // public void setMaxLength(final int maxLength); // public String soundex(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 SoundexTest extends StringEncoderAbstractTest<Soundex> { // // // @Override // protected Soundex createStringEncoder(); // @Test // public void testB650() throws EncoderException; // @Test // public void testBadCharacters(); // @Test // public void testDifference() throws EncoderException; // @Test // public void testEncodeBasic(); // @Test // public void testEncodeBatch2(); // @Test // public void testEncodeBatch3(); // @Test // public void testEncodeBatch4(); // @Test // public void testEncodeIgnoreApostrophes() throws EncoderException; // @Test // public void testEncodeIgnoreHyphens() throws EncoderException; // @Test // public void testEncodeIgnoreTrimmable(); // @Test // public void testHWRuleEx1(); // @Test // public void testHWRuleEx2(); // @Test // public void testHWRuleEx3() throws EncoderException; // @Test // public void testMsSqlServer1(); // @Test // public void testMsSqlServer2() throws EncoderException; // @Test // public void testMsSqlServer3(); // @Test // public void testNewInstance(); // @Test // public void testNewInstance2(); // @Test // public void testNewInstance3(); // @Test // public void testSoundexUtilsConstructable(); // @Test // public void testSoundexUtilsNullBehaviour(); // @Test // public void testUsEnglishStatic(); // @Test // public void testUsMappingEWithAcute(); // @Test // public void testUsMappingOWithDiaeresis(); // @Test // public void testWikipediaAmericanSoundex(); // } // You are a professional Java test case writer, please create a test case named `testHWRuleEx3` for the `Soundex` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Consonants from the same code group separated by W or H are treated as one. * * @throws EncoderException */
src/test/java/org/apache/commons/codec/language/SoundexTest.java
package org.apache.commons.codec.language; import org.apache.commons.codec.EncoderException; import org.apache.commons.codec.StringEncoder;
public Soundex(); public Soundex(final char[] mapping); public Soundex(final String mapping); public int difference(final String s1, final String s2) throws EncoderException; @Override public Object encode(final Object obj) throws EncoderException; @Override public String encode(final String str); @Deprecated public int getMaxLength(); private char[] getSoundexMapping(); private char map(final char ch); @Deprecated public void setMaxLength(final int maxLength); public String soundex(String str);
272
testHWRuleEx3
```java // Abstract Java Tested Class package org.apache.commons.codec.language; import org.apache.commons.codec.EncoderException; import org.apache.commons.codec.StringEncoder; public class Soundex implements StringEncoder { public static final String US_ENGLISH_MAPPING_STRING = "0123012#02245501262301#202"; private static final char[] US_ENGLISH_MAPPING = US_ENGLISH_MAPPING_STRING.toCharArray(); public static final Soundex US_ENGLISH = new Soundex(); @Deprecated private int maxLength = 4; private final char[] soundexMapping; public Soundex(); public Soundex(final char[] mapping); public Soundex(final String mapping); public int difference(final String s1, final String s2) throws EncoderException; @Override public Object encode(final Object obj) throws EncoderException; @Override public String encode(final String str); @Deprecated public int getMaxLength(); private char[] getSoundexMapping(); private char map(final char ch); @Deprecated public void setMaxLength(final int maxLength); public String soundex(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 SoundexTest extends StringEncoderAbstractTest<Soundex> { @Override protected Soundex createStringEncoder(); @Test public void testB650() throws EncoderException; @Test public void testBadCharacters(); @Test public void testDifference() throws EncoderException; @Test public void testEncodeBasic(); @Test public void testEncodeBatch2(); @Test public void testEncodeBatch3(); @Test public void testEncodeBatch4(); @Test public void testEncodeIgnoreApostrophes() throws EncoderException; @Test public void testEncodeIgnoreHyphens() throws EncoderException; @Test public void testEncodeIgnoreTrimmable(); @Test public void testHWRuleEx1(); @Test public void testHWRuleEx2(); @Test public void testHWRuleEx3() throws EncoderException; @Test public void testMsSqlServer1(); @Test public void testMsSqlServer2() throws EncoderException; @Test public void testMsSqlServer3(); @Test public void testNewInstance(); @Test public void testNewInstance2(); @Test public void testNewInstance3(); @Test public void testSoundexUtilsConstructable(); @Test public void testSoundexUtilsNullBehaviour(); @Test public void testUsEnglishStatic(); @Test public void testUsMappingEWithAcute(); @Test public void testUsMappingOWithDiaeresis(); @Test public void testWikipediaAmericanSoundex(); } ``` You are a professional Java test case writer, please create a test case named `testHWRuleEx3` for the `Soundex` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Consonants from the same code group separated by W or H are treated as one. * * @throws EncoderException */
250
// // Abstract Java Tested Class // package org.apache.commons.codec.language; // // import org.apache.commons.codec.EncoderException; // import org.apache.commons.codec.StringEncoder; // // // // public class Soundex implements StringEncoder { // public static final String US_ENGLISH_MAPPING_STRING = "0123012#02245501262301#202"; // private static final char[] US_ENGLISH_MAPPING = US_ENGLISH_MAPPING_STRING.toCharArray(); // public static final Soundex US_ENGLISH = new Soundex(); // @Deprecated // private int maxLength = 4; // private final char[] soundexMapping; // // public Soundex(); // public Soundex(final char[] mapping); // public Soundex(final String mapping); // public int difference(final String s1, final String s2) throws EncoderException; // @Override // public Object encode(final Object obj) throws EncoderException; // @Override // public String encode(final String str); // @Deprecated // public int getMaxLength(); // private char[] getSoundexMapping(); // private char map(final char ch); // @Deprecated // public void setMaxLength(final int maxLength); // public String soundex(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 SoundexTest extends StringEncoderAbstractTest<Soundex> { // // // @Override // protected Soundex createStringEncoder(); // @Test // public void testB650() throws EncoderException; // @Test // public void testBadCharacters(); // @Test // public void testDifference() throws EncoderException; // @Test // public void testEncodeBasic(); // @Test // public void testEncodeBatch2(); // @Test // public void testEncodeBatch3(); // @Test // public void testEncodeBatch4(); // @Test // public void testEncodeIgnoreApostrophes() throws EncoderException; // @Test // public void testEncodeIgnoreHyphens() throws EncoderException; // @Test // public void testEncodeIgnoreTrimmable(); // @Test // public void testHWRuleEx1(); // @Test // public void testHWRuleEx2(); // @Test // public void testHWRuleEx3() throws EncoderException; // @Test // public void testMsSqlServer1(); // @Test // public void testMsSqlServer2() throws EncoderException; // @Test // public void testMsSqlServer3(); // @Test // public void testNewInstance(); // @Test // public void testNewInstance2(); // @Test // public void testNewInstance3(); // @Test // public void testSoundexUtilsConstructable(); // @Test // public void testSoundexUtilsNullBehaviour(); // @Test // public void testUsEnglishStatic(); // @Test // public void testUsMappingEWithAcute(); // @Test // public void testUsMappingOWithDiaeresis(); // @Test // public void testWikipediaAmericanSoundex(); // } // You are a professional Java test case writer, please create a test case named `testHWRuleEx3` for the `Soundex` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Consonants from the same code group separated by W or H are treated as one. * * @throws EncoderException */ @Test public void testHWRuleEx3() throws EncoderException {
/** * Consonants from the same code group separated by W or H are treated as one. * * @throws EncoderException */
18
org.apache.commons.codec.language.Soundex
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.codec.language; import org.apache.commons.codec.EncoderException; import org.apache.commons.codec.StringEncoder; public class Soundex implements StringEncoder { public static final String US_ENGLISH_MAPPING_STRING = "0123012#02245501262301#202"; private static final char[] US_ENGLISH_MAPPING = US_ENGLISH_MAPPING_STRING.toCharArray(); public static final Soundex US_ENGLISH = new Soundex(); @Deprecated private int maxLength = 4; private final char[] soundexMapping; public Soundex(); public Soundex(final char[] mapping); public Soundex(final String mapping); public int difference(final String s1, final String s2) throws EncoderException; @Override public Object encode(final Object obj) throws EncoderException; @Override public String encode(final String str); @Deprecated public int getMaxLength(); private char[] getSoundexMapping(); private char map(final char ch); @Deprecated public void setMaxLength(final int maxLength); public String soundex(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 SoundexTest extends StringEncoderAbstractTest<Soundex> { @Override protected Soundex createStringEncoder(); @Test public void testB650() throws EncoderException; @Test public void testBadCharacters(); @Test public void testDifference() throws EncoderException; @Test public void testEncodeBasic(); @Test public void testEncodeBatch2(); @Test public void testEncodeBatch3(); @Test public void testEncodeBatch4(); @Test public void testEncodeIgnoreApostrophes() throws EncoderException; @Test public void testEncodeIgnoreHyphens() throws EncoderException; @Test public void testEncodeIgnoreTrimmable(); @Test public void testHWRuleEx1(); @Test public void testHWRuleEx2(); @Test public void testHWRuleEx3() throws EncoderException; @Test public void testMsSqlServer1(); @Test public void testMsSqlServer2() throws EncoderException; @Test public void testMsSqlServer3(); @Test public void testNewInstance(); @Test public void testNewInstance2(); @Test public void testNewInstance3(); @Test public void testSoundexUtilsConstructable(); @Test public void testSoundexUtilsNullBehaviour(); @Test public void testUsEnglishStatic(); @Test public void testUsMappingEWithAcute(); @Test public void testUsMappingOWithDiaeresis(); @Test public void testWikipediaAmericanSoundex(); } ``` You are a professional Java test case writer, please create a test case named `testHWRuleEx3` for the `Soundex` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Consonants from the same code group separated by W or H are treated as one. * * @throws EncoderException */ @Test public void testHWRuleEx3() throws EncoderException { ```
public class Soundex 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;
@Override protected Soundex createStringEncoder(); @Test public void testB650() throws EncoderException; @Test public void testBadCharacters(); @Test public void testDifference() throws EncoderException; @Test public void testEncodeBasic(); @Test public void testEncodeBatch2(); @Test public void testEncodeBatch3(); @Test public void testEncodeBatch4(); @Test public void testEncodeIgnoreApostrophes() throws EncoderException; @Test public void testEncodeIgnoreHyphens() throws EncoderException; @Test public void testEncodeIgnoreTrimmable(); @Test public void testHWRuleEx1(); @Test public void testHWRuleEx2(); @Test public void testHWRuleEx3() throws EncoderException; @Test public void testMsSqlServer1(); @Test public void testMsSqlServer2() throws EncoderException; @Test public void testMsSqlServer3(); @Test public void testNewInstance(); @Test public void testNewInstance2(); @Test public void testNewInstance3(); @Test public void testSoundexUtilsConstructable(); @Test public void testSoundexUtilsNullBehaviour(); @Test public void testUsEnglishStatic(); @Test public void testUsMappingEWithAcute(); @Test public void testUsMappingOWithDiaeresis(); @Test public void testWikipediaAmericanSoundex();
7d4d699124eadac3d01e43249afb7a0b393b8f4357dae98bb667c3ec2091c825
[ "org.apache.commons.codec.language.SoundexTest::testHWRuleEx3" ]
public static final String US_ENGLISH_MAPPING_STRING = "0123012#02245501262301#202"; private static final char[] US_ENGLISH_MAPPING = US_ENGLISH_MAPPING_STRING.toCharArray(); public static final Soundex US_ENGLISH = new Soundex(); @Deprecated private int maxLength = 4; private final char[] soundexMapping;
@Test public void testHWRuleEx3() throws EncoderException
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. */ // (FYI: Formatted and sorted with Eclipse) 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 Soundex}. * * <p>Keep this file in UTF-8 encoding for proper Javadoc processing.</p> * * @version $Id$ */ public class SoundexTest extends StringEncoderAbstractTest<Soundex> { @Override protected Soundex createStringEncoder() { return new Soundex(); } @Test public void testB650() throws EncoderException { this.checkEncodingVariations("B650", new String[]{ "BARHAM", "BARONE", "BARRON", "BERNA", "BIRNEY", "BIRNIE", "BOOROM", "BOREN", "BORN", "BOURN", "BOURNE", "BOWRON", "BRAIN", "BRAME", "BRANN", "BRAUN", "BREEN", "BRIEN", "BRIM", "BRIMM", "BRINN", "BRION", "BROOM", "BROOME", "BROWN", "BROWNE", "BRUEN", "BRUHN", "BRUIN", "BRUMM", "BRUN", "BRUNO", "BRYAN", "BURIAN", "BURN", "BURNEY", "BYRAM", "BYRNE", "BYRON", "BYRUM"}); } @Test public void testBadCharacters() { Assert.assertEquals("H452", this.getStringEncoder().encode("HOL>MES")); } @Test public void testDifference() throws EncoderException { // Edge cases Assert.assertEquals(0, this.getStringEncoder().difference(null, null)); Assert.assertEquals(0, this.getStringEncoder().difference("", "")); Assert.assertEquals(0, this.getStringEncoder().difference(" ", " ")); // Normal cases Assert.assertEquals(4, this.getStringEncoder().difference("Smith", "Smythe")); Assert.assertEquals(2, this.getStringEncoder().difference("Ann", "Andrew")); Assert.assertEquals(1, this.getStringEncoder().difference("Margaret", "Andrew")); Assert.assertEquals(0, this.getStringEncoder().difference("Janet", "Margaret")); // Examples from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_de-dz_8co5.asp Assert.assertEquals(4, this.getStringEncoder().difference("Green", "Greene")); Assert.assertEquals(0, this.getStringEncoder().difference("Blotchet-Halls", "Greene")); // Examples from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_setu-sus_3o6w.asp Assert.assertEquals(4, this.getStringEncoder().difference("Smith", "Smythe")); Assert.assertEquals(4, this.getStringEncoder().difference("Smithers", "Smythers")); Assert.assertEquals(2, this.getStringEncoder().difference("Anothers", "Brothers")); } @Test public void testEncodeBasic() { Assert.assertEquals("T235", this.getStringEncoder().encode("testing")); Assert.assertEquals("T000", this.getStringEncoder().encode("The")); Assert.assertEquals("Q200", this.getStringEncoder().encode("quick")); Assert.assertEquals("B650", this.getStringEncoder().encode("brown")); Assert.assertEquals("F200", this.getStringEncoder().encode("fox")); Assert.assertEquals("J513", this.getStringEncoder().encode("jumped")); Assert.assertEquals("O160", this.getStringEncoder().encode("over")); Assert.assertEquals("T000", this.getStringEncoder().encode("the")); Assert.assertEquals("L200", this.getStringEncoder().encode("lazy")); Assert.assertEquals("D200", this.getStringEncoder().encode("dogs")); } /** * Examples from http://www.bradandkathy.com/genealogy/overviewofsoundex.html */ @Test public void testEncodeBatch2() { Assert.assertEquals("A462", this.getStringEncoder().encode("Allricht")); Assert.assertEquals("E166", this.getStringEncoder().encode("Eberhard")); Assert.assertEquals("E521", this.getStringEncoder().encode("Engebrethson")); Assert.assertEquals("H512", this.getStringEncoder().encode("Heimbach")); Assert.assertEquals("H524", this.getStringEncoder().encode("Hanselmann")); Assert.assertEquals("H431", this.getStringEncoder().encode("Hildebrand")); Assert.assertEquals("K152", this.getStringEncoder().encode("Kavanagh")); Assert.assertEquals("L530", this.getStringEncoder().encode("Lind")); Assert.assertEquals("L222", this.getStringEncoder().encode("Lukaschowsky")); Assert.assertEquals("M235", this.getStringEncoder().encode("McDonnell")); Assert.assertEquals("M200", this.getStringEncoder().encode("McGee")); Assert.assertEquals("O155", this.getStringEncoder().encode("Opnian")); Assert.assertEquals("O155", this.getStringEncoder().encode("Oppenheimer")); Assert.assertEquals("R355", this.getStringEncoder().encode("Riedemanas")); Assert.assertEquals("Z300", this.getStringEncoder().encode("Zita")); Assert.assertEquals("Z325", this.getStringEncoder().encode("Zitzmeinn")); } /** * Examples from http://www.archives.gov/research_room/genealogy/census/soundex.html */ @Test public void testEncodeBatch3() { Assert.assertEquals("W252", this.getStringEncoder().encode("Washington")); Assert.assertEquals("L000", this.getStringEncoder().encode("Lee")); Assert.assertEquals("G362", this.getStringEncoder().encode("Gutierrez")); Assert.assertEquals("P236", this.getStringEncoder().encode("Pfister")); Assert.assertEquals("J250", this.getStringEncoder().encode("Jackson")); Assert.assertEquals("T522", this.getStringEncoder().encode("Tymczak")); // For VanDeusen: D-250 (D, 2 for the S, 5 for the N, 0 added) is also // possible. Assert.assertEquals("V532", this.getStringEncoder().encode("VanDeusen")); } /** * Examples from: http://www.myatt.demon.co.uk/sxalg.htm */ @Test public void testEncodeBatch4() { Assert.assertEquals("H452", this.getStringEncoder().encode("HOLMES")); Assert.assertEquals("A355", this.getStringEncoder().encode("ADOMOMI")); Assert.assertEquals("V536", this.getStringEncoder().encode("VONDERLEHR")); Assert.assertEquals("B400", this.getStringEncoder().encode("BALL")); Assert.assertEquals("S000", this.getStringEncoder().encode("SHAW")); Assert.assertEquals("J250", this.getStringEncoder().encode("JACKSON")); Assert.assertEquals("S545", this.getStringEncoder().encode("SCANLON")); Assert.assertEquals("S532", this.getStringEncoder().encode("SAINTJOHN")); } @Test public void testEncodeIgnoreApostrophes() throws EncoderException { this.checkEncodingVariations("O165", new String[]{ "OBrien", "'OBrien", "O'Brien", "OB'rien", "OBr'ien", "OBri'en", "OBrie'n", "OBrien'"}); } /** * Test data from http://www.myatt.demon.co.uk/sxalg.htm * * @throws EncoderException */ @Test public void testEncodeIgnoreHyphens() throws EncoderException { this.checkEncodingVariations("K525", new String[]{ "KINGSMITH", "-KINGSMITH", "K-INGSMITH", "KI-NGSMITH", "KIN-GSMITH", "KING-SMITH", "KINGS-MITH", "KINGSM-ITH", "KINGSMI-TH", "KINGSMIT-H", "KINGSMITH-"}); } @Test public void testEncodeIgnoreTrimmable() { Assert.assertEquals("W252", this.getStringEncoder().encode(" \t\n\r Washington \t\n\r ")); } /** * Consonants from the same code group separated by W or H are treated as one. */ @Test public void testHWRuleEx1() { // From // http://www.archives.gov/research_room/genealogy/census/soundex.html: // Ashcraft is coded A-261 (A, 2 for the S, C ignored, 6 for the R, 1 // for the F). It is not coded A-226. Assert.assertEquals("A261", this.getStringEncoder().encode("Ashcraft")); Assert.assertEquals("A261", this.getStringEncoder().encode("Ashcroft")); Assert.assertEquals("Y330", this.getStringEncoder().encode("yehudit")); Assert.assertEquals("Y330", this.getStringEncoder().encode("yhwdyt")); } /** * Consonants from the same code group separated by W or H are treated as one. * * Test data from http://www.myatt.demon.co.uk/sxalg.htm */ @Test public void testHWRuleEx2() { Assert.assertEquals("B312", this.getStringEncoder().encode("BOOTHDAVIS")); Assert.assertEquals("B312", this.getStringEncoder().encode("BOOTH-DAVIS")); } /** * Consonants from the same code group separated by W or H are treated as one. * * @throws EncoderException */ @Test public void testHWRuleEx3() throws EncoderException { Assert.assertEquals("S460", this.getStringEncoder().encode("Sgler")); Assert.assertEquals("S460", this.getStringEncoder().encode("Swhgler")); // Also S460: this.checkEncodingVariations("S460", new String[]{ "SAILOR", "SALYER", "SAYLOR", "SCHALLER", "SCHELLER", "SCHILLER", "SCHOOLER", "SCHULER", "SCHUYLER", "SEILER", "SEYLER", "SHOLAR", "SHULER", "SILAR", "SILER", "SILLER"}); } /** * Examples for MS SQLServer from * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_setu-sus_3o6w.asp */ @Test public void testMsSqlServer1() { Assert.assertEquals("S530", this.getStringEncoder().encode("Smith")); Assert.assertEquals("S530", this.getStringEncoder().encode("Smythe")); } /** * Examples for MS SQLServer from * http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support * /kb/articles/Q100/3/65.asp&NoWebContent=1 * * @throws EncoderException */ @Test public void testMsSqlServer2() throws EncoderException { this.checkEncodingVariations("E625", new String[]{"Erickson", "Erickson", "Erikson", "Ericson", "Ericksen", "Ericsen"}); } /** * Examples for MS SQLServer from http://databases.about.com/library/weekly/aa042901a.htm */ @Test public void testMsSqlServer3() { Assert.assertEquals("A500", this.getStringEncoder().encode("Ann")); Assert.assertEquals("A536", this.getStringEncoder().encode("Andrew")); Assert.assertEquals("J530", this.getStringEncoder().encode("Janet")); Assert.assertEquals("M626", this.getStringEncoder().encode("Margaret")); Assert.assertEquals("S315", this.getStringEncoder().encode("Steven")); Assert.assertEquals("M240", this.getStringEncoder().encode("Michael")); Assert.assertEquals("R163", this.getStringEncoder().encode("Robert")); Assert.assertEquals("L600", this.getStringEncoder().encode("Laura")); Assert.assertEquals("A500", this.getStringEncoder().encode("Anne")); } /** * https://issues.apache.org/jira/browse/CODEC-54 https://issues.apache.org/jira/browse/CODEC-56 */ @Test public void testNewInstance() { Assert.assertEquals("W452", new Soundex().soundex("Williams")); } @Test public void testNewInstance2() { Assert.assertEquals("W452", new Soundex(Soundex.US_ENGLISH_MAPPING_STRING.toCharArray()).soundex("Williams")); } @Test public void testNewInstance3() { Assert.assertEquals("W452", new Soundex(Soundex.US_ENGLISH_MAPPING_STRING).soundex("Williams")); } @Test public void testSoundexUtilsConstructable() { new SoundexUtils(); } @Test public void testSoundexUtilsNullBehaviour() { Assert.assertEquals(null, SoundexUtils.clean(null)); Assert.assertEquals("", SoundexUtils.clean("")); Assert.assertEquals(0, SoundexUtils.differenceEncoded(null, "")); Assert.assertEquals(0, SoundexUtils.differenceEncoded("", null)); } /** * https://issues.apache.org/jira/browse/CODEC-54 https://issues.apache.org/jira/browse/CODEC-56 */ @Test public void testUsEnglishStatic() { Assert.assertEquals("W452", Soundex.US_ENGLISH.soundex("Williams")); } /** * Fancy characters are not mapped by the default US mapping. * * http://issues.apache.org/bugzilla/show_bug.cgi?id=29080 */ @Test public void testUsMappingEWithAcute() { Assert.assertEquals("E000", this.getStringEncoder().encode("e")); if (Character.isLetter('\u00e9')) { // e-acute try { // uppercase E-acute Assert.assertEquals("\u00c9000", this.getStringEncoder().encode("\u00e9")); Assert.fail("Expected IllegalArgumentException not thrown"); } catch (final IllegalArgumentException e) { // expected } } else { Assert.assertEquals("", this.getStringEncoder().encode("\u00e9")); } } /** * Fancy characters are not mapped by the default US mapping. * * http://issues.apache.org/bugzilla/show_bug.cgi?id=29080 */ @Test public void testUsMappingOWithDiaeresis() { Assert.assertEquals("O000", this.getStringEncoder().encode("o")); if (Character.isLetter('\u00f6')) { // o-umlaut try { // uppercase O-umlaut Assert.assertEquals("\u00d6000", this.getStringEncoder().encode("\u00f6")); Assert.fail("Expected IllegalArgumentException not thrown"); } catch (final IllegalArgumentException e) { // expected } } else { Assert.assertEquals("", this.getStringEncoder().encode("\u00f6")); } } /** * Tests example from http://en.wikipedia.org/wiki/Soundex#American_Soundex as of 2015-03-22. */ @Test public void testWikipediaAmericanSoundex() { Assert.assertEquals("R163", this.getStringEncoder().encode("Robert")); Assert.assertEquals("R163", this.getStringEncoder().encode("Rupert")); Assert.assertEquals("A261", this.getStringEncoder().encode("Ashcraft")); Assert.assertEquals("A261", this.getStringEncoder().encode("Ashcroft")); Assert.assertEquals("T522", this.getStringEncoder().encode("Tymczak")); Assert.assertEquals("P236", this.getStringEncoder().encode("Pfister")); } }
[ { "be_test_class_file": "org/apache/commons/codec/language/Soundex.java", "be_test_class_name": "org.apache.commons.codec.language.Soundex", "be_test_function_name": "encode", "be_test_function_signature": "(Ljava/lang/String;)Ljava/lang/String;", "line_numbers": [ "167" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/codec/language/Soundex.java", "be_test_class_name": "org.apache.commons.codec.language.Soundex", "be_test_function_name": "getSoundexMapping", "be_test_function_signature": "()[C", "line_numbers": [ "187" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/codec/language/Soundex.java", "be_test_class_name": "org.apache.commons.codec.language.Soundex", "be_test_function_name": "map", "be_test_function_signature": "(C)C", "line_numbers": [ "200", "201", "202", "204" ], "method_line_rate": 0.75 }, { "be_test_class_file": "org/apache/commons/codec/language/Soundex.java", "be_test_class_name": "org.apache.commons.codec.language.Soundex", "be_test_function_name": "soundex", "be_test_function_signature": "(Ljava/lang/String;)Ljava/lang/String;", "line_numbers": [ "229", "230", "232", "233", "234", "236", "238", "239", "241", "242", "243", "244", "245", "246", "247", "248", "251" ], "method_line_rate": 0.8823529411764706 } ]
public class MultiBackgroundInitializerTest
@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()); }
// // 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 `testInitializeEx` for the `MultiBackgroundInitializer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests the behavior of the initializer if one of the child initializers * throws a checked exception. */
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);
285
testInitializeEx
```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 `testInitializeEx` for the `MultiBackgroundInitializer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests the behavior of the initializer if one of the child initializers * throws a checked exception. */
273
// // 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 `testInitializeEx` for the `MultiBackgroundInitializer` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests the behavior of the initializer if one of the child initializers * throws a checked exception. */ @Test public void testInitializeEx() throws ConcurrentException {
/** * Tests the behavior of the initializer if one of the child initializers * throws a checked exception. */
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 `testInitializeEx` for the `MultiBackgroundInitializer` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests the behavior of the initializer if one of the child initializers * throws a checked exception. */ @Test public void testInitializeEx() 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;
80852c9c2bb5d4c8ed3408d9dd0859bf689375016db116069ee24ab7d8ce5bde
[ "org.apache.commons.lang3.concurrent.MultiBackgroundInitializerTest::testInitializeEx" ]
private final Map<String, BackgroundInitializer<?>> childInitializers = new HashMap<String, BackgroundInitializer<?>>();
@Test public void testInitializeEx() 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.9444444444444444 } ]
public class TypeCheckTest extends CompilerTypeTestCase
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 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 `testBug911118` for the `TypeCheck` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */
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);
7,026
testBug911118
```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 `testBug911118` for the `TypeCheck` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */
7,015
// 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 `testBug911118` for the `TypeCheck` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() throws Exception {
/** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */
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 `testBug911118` for the `TypeCheck` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests that assigning two untyped functions to a variable whose type is * inferred and calling this variable is legal. */ public void testBug911118() 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);
838cd9528d0dc75efd6d0fb5afe9c794f64c86b715efd34d53897f41e6ac99b7
[ "com.google.javascript.jscomp.TypeCheckTest::testBug911118" ]
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 testBug911118() 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.1686046511627907 }, { "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.5714285714285714 }, { "be_test_class_file": "com/google/javascript/jscomp/TypeCheck.java", "be_test_class_name": "com.google.javascript.jscomp.TypeCheck", "be_test_function_name": "visitCall", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "1778", "1779", "1781", "1782", "1783", "1784", "1789", "1790", "1794", "1798", "1803", "1809", "1812", "1813", "1814", "1815", "1821" ], "method_line_rate": 0.6470588235294118 }, { "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": "visitParameterList", "be_test_function_signature": "(Lcom/google/javascript/jscomp/NodeTraversal;Lcom/google/javascript/rhino/Node;Lcom/google/javascript/rhino/jstype/FunctionType;)V", "line_numbers": [ "1828", "1829", "1831", "1832", "1833", "1834", "1835", "1840", "1841", "1843", "1844", "1846", "1850", "1851", "1852", "1853", "1854", "1860" ], "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": "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": 1 } ]
public class MillerUpdatingRegressionTest
@Test public void testRegressAirlineConstantExternal() { MillerUpdatingRegression instance = new MillerUpdatingRegression(4, false); double[][] x = new double[airdata[0].length][]; double[] y = new double[airdata[0].length]; for (int i = 0; i < airdata[0].length; i++) { x[i] = new double[4]; x[i][0] = 1.0; x[i][1] = Math.log(airdata[3][i]); x[i][2] = Math.log(airdata[4][i]); x[i][3] = airdata[5][i]; y[i] = Math.log(airdata[2][i]); } instance.addObservations(x, y); try { RegressionResults result = instance.regress(); Assert.assertNotNull("The test case is a prototype.", result); TestUtils.assertEquals( new double[]{9.5169, 0.8827, 0.4540, -1.6275}, result.getParameterEstimates(), 1e-4); TestUtils.assertEquals( new double[]{.2292445, .0132545, .0203042, .345302}, result.getStdErrorOfEstimates(), 1.0e-4); TestUtils.assertEquals(0.01552839, result.getMeanSquareError(), 1.0e-8); } catch (Exception e) { Assert.fail("Should not throw exception but does"); } }
// /*"Q",*/ new double[]{0.952757, 0.986757, 1.09198, 1.17578, 1.16017, 1.17376, 1.29051, 1.39067, 1.61273, 1.82544, 1.54604, 1.5279, 1.6602, 1.82231, 1.93646, 0.520635, 0.534627, 0.655192, 0.791575, 0.842945, 0.852892, 0.922843, 1, 1.19845, 1.34067, 1.32624, 1.24852, 1.25432, 1.37177, 1.38974, 0.262424, 0.266433, 0.306043, 0.325586, 0.345706, 0.367517, 0.409937, 0.448023, 0.539595, 0.539382, 0.467967, 0.450544, 0.468793, 0.494397, 0.493317, 0.086393, 0.09674, 0.1415, 0.169715, 0.173805, 0.164272, 0.170906, 0.17784, 0.192248, 0.242469, 0.256505, 0.249657, 0.273923, 0.371131, 0.421411, 0.051028, 0.052646, 0.056348, 0.066953, 0.070308, 0.073961, 0.084946, 0.095474, 0.119814, 0.150046, 0.144014, 0.1693, 0.172761, 0.18667, 0.213279, 0.037682, 0.039784, 0.044331, 0.050245, 0.055046, 0.052462, 0.056977, 0.06149, 0.069027, 0.092749, 0.11264, 0.154154, 0.186461, 0.246847, 0.304013}, // /*"PF",*/ new double[]{106650, 110307, 110574, 121974, 196606, 265609, 263451, 316411, 384110, 569251, 871636, 997239, 938002, 859572, 823411, 103795, 111477, 118664, 114797, 215322, 281704, 304818, 348609, 374579, 544109, 853356, 1003200, 941977, 856533, 821361, 118788, 123798, 122882, 131274, 222037, 278721, 306564, 356073, 378311, 555267, 850322, 1015610, 954508, 886999, 844079, 114987, 120501, 121908, 127220, 209405, 263148, 316724, 363598, 389436, 547376, 850418, 1011170, 951934, 881323, 831374, 118222, 116223, 115853, 129372, 243266, 277930, 317273, 358794, 397667, 566672, 848393, 1005740, 958231, 872924, 844622, 117112, 119420, 116087, 122997, 194309, 307923, 323595, 363081, 386422, 564867, 874818, 1013170, 930477, 851676, 819476}, // /*"LF",*/ new double[]{0.534487, 0.532328, 0.547736, 0.540846, 0.591167, 0.575417, 0.594495, 0.597409, 0.638522, 0.676287, 0.605735, 0.61436, 0.633366, 0.650117, 0.625603, 0.490851, 0.473449, 0.503013, 0.512501, 0.566782, 0.558133, 0.558799, 0.57207, 0.624763, 0.628706, 0.58915, 0.532612, 0.526652, 0.540163, 0.528775, 0.524334, 0.537185, 0.582119, 0.579489, 0.606592, 0.60727, 0.582425, 0.573972, 0.654256, 0.631055, 0.56924, 0.589682, 0.587953, 0.565388, 0.577078, 0.432066, 0.439669, 0.488932, 0.484181, 0.529925, 0.532723, 0.549067, 0.55714, 0.611377, 0.645319, 0.611734, 0.580884, 0.572047, 0.59457, 0.585525, 0.442875, 0.462473, 0.519118, 0.529331, 0.557797, 0.556181, 0.569327, 0.583465, 0.631818, 0.604723, 0.587921, 0.616159, 0.605868, 0.594688, 0.635545, 0.448539, 0.475889, 0.500562, 0.500344, 0.528897, 0.495361, 0.510342, 0.518296, 0.546723, 0.554276, 0.517766, 0.580049, 0.556024, 0.537791, 0.525775} // }; // // public MillerUpdatingRegressionTest(); // @Test // public void testHasIntercept(); // @Test // public void testAddObsGetNClear(); // @Test // public void testNegativeTestAddObs(); // @Test // public void testNegativeTestAddMultipleObs(); // @Test // public void testRegressAirlineConstantExternal(); // @Test // public void testRegressAirlineConstantInternal(); // @Test // public void testFilippelli(); // @Test // public void testWampler1(); // @Test // public void testWampler2(); // @Test // public void testWampler3(); // public void testWampler4(); // @Test // public void testLongly(); // @Test // public void testOneRedundantColumn(); // @Test // public void testThreeRedundantColumn(); // @Test // public void testPCorr(); // @Test // public void testHdiag(); // @Test // public void testHdiagConstant(); // @Test // public void testSubsetRegression(); // } // You are a professional Java test case writer, please create a test case named `testRegressAirlineConstantExternal` for the `MillerUpdatingRegression` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* Results can be found at http://www.indiana.edu/~statmath/stat/all/panel/panel4.html * This test concerns a known data set */
src/test/java/org/apache/commons/math3/stat/regression/MillerUpdatingRegressionTest.java
package org.apache.commons.math3.stat.regression; import java.util.Arrays; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.Precision; import org.apache.commons.math3.util.MathArrays;
@SuppressWarnings("unused") private MillerUpdatingRegression(); public MillerUpdatingRegression(int numberOfVariables, boolean includeConstant, double errorTolerance) throws ModelSpecificationException; public MillerUpdatingRegression(int numberOfVariables, boolean includeConstant) throws ModelSpecificationException; public boolean hasIntercept(); public long getN(); public void addObservation(final double[] x, final double y) throws ModelSpecificationException; public void addObservations(double[][] x, double[] y) throws ModelSpecificationException; private void include(final double[] x, final double wi, final double yi); private double smartAdd(double a, double b); public void clear(); private void tolset(); private double[] regcf(int nreq) throws ModelSpecificationException; private void singcheck(); private void ss(); private double[] cov(int nreq); private void inverse(double[] rinv, int nreq); public double[] getPartialCorrelations(int in); private void vmove(int from, int to); private int reorderRegressors(int[] list, int pos1); public double getDiagonalOfHatMatrix(double[] row_data); public int[] getOrderOfRegressors(); public RegressionResults regress() throws ModelSpecificationException; public RegressionResults regress(int numberOfRegressors) throws ModelSpecificationException; public RegressionResults regress(int[] variablesToInclude) throws ModelSpecificationException;
194
testRegressAirlineConstantExternal
```java /*"Q",*/ new double[]{0.952757, 0.986757, 1.09198, 1.17578, 1.16017, 1.17376, 1.29051, 1.39067, 1.61273, 1.82544, 1.54604, 1.5279, 1.6602, 1.82231, 1.93646, 0.520635, 0.534627, 0.655192, 0.791575, 0.842945, 0.852892, 0.922843, 1, 1.19845, 1.34067, 1.32624, 1.24852, 1.25432, 1.37177, 1.38974, 0.262424, 0.266433, 0.306043, 0.325586, 0.345706, 0.367517, 0.409937, 0.448023, 0.539595, 0.539382, 0.467967, 0.450544, 0.468793, 0.494397, 0.493317, 0.086393, 0.09674, 0.1415, 0.169715, 0.173805, 0.164272, 0.170906, 0.17784, 0.192248, 0.242469, 0.256505, 0.249657, 0.273923, 0.371131, 0.421411, 0.051028, 0.052646, 0.056348, 0.066953, 0.070308, 0.073961, 0.084946, 0.095474, 0.119814, 0.150046, 0.144014, 0.1693, 0.172761, 0.18667, 0.213279, 0.037682, 0.039784, 0.044331, 0.050245, 0.055046, 0.052462, 0.056977, 0.06149, 0.069027, 0.092749, 0.11264, 0.154154, 0.186461, 0.246847, 0.304013}, /*"PF",*/ new double[]{106650, 110307, 110574, 121974, 196606, 265609, 263451, 316411, 384110, 569251, 871636, 997239, 938002, 859572, 823411, 103795, 111477, 118664, 114797, 215322, 281704, 304818, 348609, 374579, 544109, 853356, 1003200, 941977, 856533, 821361, 118788, 123798, 122882, 131274, 222037, 278721, 306564, 356073, 378311, 555267, 850322, 1015610, 954508, 886999, 844079, 114987, 120501, 121908, 127220, 209405, 263148, 316724, 363598, 389436, 547376, 850418, 1011170, 951934, 881323, 831374, 118222, 116223, 115853, 129372, 243266, 277930, 317273, 358794, 397667, 566672, 848393, 1005740, 958231, 872924, 844622, 117112, 119420, 116087, 122997, 194309, 307923, 323595, 363081, 386422, 564867, 874818, 1013170, 930477, 851676, 819476}, /*"LF",*/ new double[]{0.534487, 0.532328, 0.547736, 0.540846, 0.591167, 0.575417, 0.594495, 0.597409, 0.638522, 0.676287, 0.605735, 0.61436, 0.633366, 0.650117, 0.625603, 0.490851, 0.473449, 0.503013, 0.512501, 0.566782, 0.558133, 0.558799, 0.57207, 0.624763, 0.628706, 0.58915, 0.532612, 0.526652, 0.540163, 0.528775, 0.524334, 0.537185, 0.582119, 0.579489, 0.606592, 0.60727, 0.582425, 0.573972, 0.654256, 0.631055, 0.56924, 0.589682, 0.587953, 0.565388, 0.577078, 0.432066, 0.439669, 0.488932, 0.484181, 0.529925, 0.532723, 0.549067, 0.55714, 0.611377, 0.645319, 0.611734, 0.580884, 0.572047, 0.59457, 0.585525, 0.442875, 0.462473, 0.519118, 0.529331, 0.557797, 0.556181, 0.569327, 0.583465, 0.631818, 0.604723, 0.587921, 0.616159, 0.605868, 0.594688, 0.635545, 0.448539, 0.475889, 0.500562, 0.500344, 0.528897, 0.495361, 0.510342, 0.518296, 0.546723, 0.554276, 0.517766, 0.580049, 0.556024, 0.537791, 0.525775} }; public MillerUpdatingRegressionTest(); @Test public void testHasIntercept(); @Test public void testAddObsGetNClear(); @Test public void testNegativeTestAddObs(); @Test public void testNegativeTestAddMultipleObs(); @Test public void testRegressAirlineConstantExternal(); @Test public void testRegressAirlineConstantInternal(); @Test public void testFilippelli(); @Test public void testWampler1(); @Test public void testWampler2(); @Test public void testWampler3(); public void testWampler4(); @Test public void testLongly(); @Test public void testOneRedundantColumn(); @Test public void testThreeRedundantColumn(); @Test public void testPCorr(); @Test public void testHdiag(); @Test public void testHdiagConstant(); @Test public void testSubsetRegression(); } ``` You are a professional Java test case writer, please create a test case named `testRegressAirlineConstantExternal` for the `MillerUpdatingRegression` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* Results can be found at http://www.indiana.edu/~statmath/stat/all/panel/panel4.html * This test concerns a known data set */
163
// /*"Q",*/ new double[]{0.952757, 0.986757, 1.09198, 1.17578, 1.16017, 1.17376, 1.29051, 1.39067, 1.61273, 1.82544, 1.54604, 1.5279, 1.6602, 1.82231, 1.93646, 0.520635, 0.534627, 0.655192, 0.791575, 0.842945, 0.852892, 0.922843, 1, 1.19845, 1.34067, 1.32624, 1.24852, 1.25432, 1.37177, 1.38974, 0.262424, 0.266433, 0.306043, 0.325586, 0.345706, 0.367517, 0.409937, 0.448023, 0.539595, 0.539382, 0.467967, 0.450544, 0.468793, 0.494397, 0.493317, 0.086393, 0.09674, 0.1415, 0.169715, 0.173805, 0.164272, 0.170906, 0.17784, 0.192248, 0.242469, 0.256505, 0.249657, 0.273923, 0.371131, 0.421411, 0.051028, 0.052646, 0.056348, 0.066953, 0.070308, 0.073961, 0.084946, 0.095474, 0.119814, 0.150046, 0.144014, 0.1693, 0.172761, 0.18667, 0.213279, 0.037682, 0.039784, 0.044331, 0.050245, 0.055046, 0.052462, 0.056977, 0.06149, 0.069027, 0.092749, 0.11264, 0.154154, 0.186461, 0.246847, 0.304013}, // /*"PF",*/ new double[]{106650, 110307, 110574, 121974, 196606, 265609, 263451, 316411, 384110, 569251, 871636, 997239, 938002, 859572, 823411, 103795, 111477, 118664, 114797, 215322, 281704, 304818, 348609, 374579, 544109, 853356, 1003200, 941977, 856533, 821361, 118788, 123798, 122882, 131274, 222037, 278721, 306564, 356073, 378311, 555267, 850322, 1015610, 954508, 886999, 844079, 114987, 120501, 121908, 127220, 209405, 263148, 316724, 363598, 389436, 547376, 850418, 1011170, 951934, 881323, 831374, 118222, 116223, 115853, 129372, 243266, 277930, 317273, 358794, 397667, 566672, 848393, 1005740, 958231, 872924, 844622, 117112, 119420, 116087, 122997, 194309, 307923, 323595, 363081, 386422, 564867, 874818, 1013170, 930477, 851676, 819476}, // /*"LF",*/ new double[]{0.534487, 0.532328, 0.547736, 0.540846, 0.591167, 0.575417, 0.594495, 0.597409, 0.638522, 0.676287, 0.605735, 0.61436, 0.633366, 0.650117, 0.625603, 0.490851, 0.473449, 0.503013, 0.512501, 0.566782, 0.558133, 0.558799, 0.57207, 0.624763, 0.628706, 0.58915, 0.532612, 0.526652, 0.540163, 0.528775, 0.524334, 0.537185, 0.582119, 0.579489, 0.606592, 0.60727, 0.582425, 0.573972, 0.654256, 0.631055, 0.56924, 0.589682, 0.587953, 0.565388, 0.577078, 0.432066, 0.439669, 0.488932, 0.484181, 0.529925, 0.532723, 0.549067, 0.55714, 0.611377, 0.645319, 0.611734, 0.580884, 0.572047, 0.59457, 0.585525, 0.442875, 0.462473, 0.519118, 0.529331, 0.557797, 0.556181, 0.569327, 0.583465, 0.631818, 0.604723, 0.587921, 0.616159, 0.605868, 0.594688, 0.635545, 0.448539, 0.475889, 0.500562, 0.500344, 0.528897, 0.495361, 0.510342, 0.518296, 0.546723, 0.554276, 0.517766, 0.580049, 0.556024, 0.537791, 0.525775} // }; // // public MillerUpdatingRegressionTest(); // @Test // public void testHasIntercept(); // @Test // public void testAddObsGetNClear(); // @Test // public void testNegativeTestAddObs(); // @Test // public void testNegativeTestAddMultipleObs(); // @Test // public void testRegressAirlineConstantExternal(); // @Test // public void testRegressAirlineConstantInternal(); // @Test // public void testFilippelli(); // @Test // public void testWampler1(); // @Test // public void testWampler2(); // @Test // public void testWampler3(); // public void testWampler4(); // @Test // public void testLongly(); // @Test // public void testOneRedundantColumn(); // @Test // public void testThreeRedundantColumn(); // @Test // public void testPCorr(); // @Test // public void testHdiag(); // @Test // public void testHdiagConstant(); // @Test // public void testSubsetRegression(); // } // You are a professional Java test case writer, please create a test case named `testRegressAirlineConstantExternal` for the `MillerUpdatingRegression` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* Results can be found at http://www.indiana.edu/~statmath/stat/all/panel/panel4.html * This test concerns a known data set */ @Test public void testRegressAirlineConstantExternal() {
/* Results can be found at http://www.indiana.edu/~statmath/stat/all/panel/panel4.html * This test concerns a known data set */
1
org.apache.commons.math3.stat.regression.MillerUpdatingRegression
src/test/java
```java /*"Q",*/ new double[]{0.952757, 0.986757, 1.09198, 1.17578, 1.16017, 1.17376, 1.29051, 1.39067, 1.61273, 1.82544, 1.54604, 1.5279, 1.6602, 1.82231, 1.93646, 0.520635, 0.534627, 0.655192, 0.791575, 0.842945, 0.852892, 0.922843, 1, 1.19845, 1.34067, 1.32624, 1.24852, 1.25432, 1.37177, 1.38974, 0.262424, 0.266433, 0.306043, 0.325586, 0.345706, 0.367517, 0.409937, 0.448023, 0.539595, 0.539382, 0.467967, 0.450544, 0.468793, 0.494397, 0.493317, 0.086393, 0.09674, 0.1415, 0.169715, 0.173805, 0.164272, 0.170906, 0.17784, 0.192248, 0.242469, 0.256505, 0.249657, 0.273923, 0.371131, 0.421411, 0.051028, 0.052646, 0.056348, 0.066953, 0.070308, 0.073961, 0.084946, 0.095474, 0.119814, 0.150046, 0.144014, 0.1693, 0.172761, 0.18667, 0.213279, 0.037682, 0.039784, 0.044331, 0.050245, 0.055046, 0.052462, 0.056977, 0.06149, 0.069027, 0.092749, 0.11264, 0.154154, 0.186461, 0.246847, 0.304013}, /*"PF",*/ new double[]{106650, 110307, 110574, 121974, 196606, 265609, 263451, 316411, 384110, 569251, 871636, 997239, 938002, 859572, 823411, 103795, 111477, 118664, 114797, 215322, 281704, 304818, 348609, 374579, 544109, 853356, 1003200, 941977, 856533, 821361, 118788, 123798, 122882, 131274, 222037, 278721, 306564, 356073, 378311, 555267, 850322, 1015610, 954508, 886999, 844079, 114987, 120501, 121908, 127220, 209405, 263148, 316724, 363598, 389436, 547376, 850418, 1011170, 951934, 881323, 831374, 118222, 116223, 115853, 129372, 243266, 277930, 317273, 358794, 397667, 566672, 848393, 1005740, 958231, 872924, 844622, 117112, 119420, 116087, 122997, 194309, 307923, 323595, 363081, 386422, 564867, 874818, 1013170, 930477, 851676, 819476}, /*"LF",*/ new double[]{0.534487, 0.532328, 0.547736, 0.540846, 0.591167, 0.575417, 0.594495, 0.597409, 0.638522, 0.676287, 0.605735, 0.61436, 0.633366, 0.650117, 0.625603, 0.490851, 0.473449, 0.503013, 0.512501, 0.566782, 0.558133, 0.558799, 0.57207, 0.624763, 0.628706, 0.58915, 0.532612, 0.526652, 0.540163, 0.528775, 0.524334, 0.537185, 0.582119, 0.579489, 0.606592, 0.60727, 0.582425, 0.573972, 0.654256, 0.631055, 0.56924, 0.589682, 0.587953, 0.565388, 0.577078, 0.432066, 0.439669, 0.488932, 0.484181, 0.529925, 0.532723, 0.549067, 0.55714, 0.611377, 0.645319, 0.611734, 0.580884, 0.572047, 0.59457, 0.585525, 0.442875, 0.462473, 0.519118, 0.529331, 0.557797, 0.556181, 0.569327, 0.583465, 0.631818, 0.604723, 0.587921, 0.616159, 0.605868, 0.594688, 0.635545, 0.448539, 0.475889, 0.500562, 0.500344, 0.528897, 0.495361, 0.510342, 0.518296, 0.546723, 0.554276, 0.517766, 0.580049, 0.556024, 0.537791, 0.525775} }; public MillerUpdatingRegressionTest(); @Test public void testHasIntercept(); @Test public void testAddObsGetNClear(); @Test public void testNegativeTestAddObs(); @Test public void testNegativeTestAddMultipleObs(); @Test public void testRegressAirlineConstantExternal(); @Test public void testRegressAirlineConstantInternal(); @Test public void testFilippelli(); @Test public void testWampler1(); @Test public void testWampler2(); @Test public void testWampler3(); public void testWampler4(); @Test public void testLongly(); @Test public void testOneRedundantColumn(); @Test public void testThreeRedundantColumn(); @Test public void testPCorr(); @Test public void testHdiag(); @Test public void testHdiagConstant(); @Test public void testSubsetRegression(); } ``` You are a professional Java test case writer, please create a test case named `testRegressAirlineConstantExternal` for the `MillerUpdatingRegression` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* Results can be found at http://www.indiana.edu/~statmath/stat/all/panel/panel4.html * This test concerns a known data set */ @Test public void testRegressAirlineConstantExternal() { ```
public class MillerUpdatingRegression implements UpdatingMultipleLinearRegression
package org.apache.commons.math3.stat.regression; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.stat.correlation.PearsonsCorrelation; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test;
public MillerUpdatingRegressionTest(); @Test public void testHasIntercept(); @Test public void testAddObsGetNClear(); @Test public void testNegativeTestAddObs(); @Test public void testNegativeTestAddMultipleObs(); @Test public void testRegressAirlineConstantExternal(); @Test public void testRegressAirlineConstantInternal(); @Test public void testFilippelli(); @Test public void testWampler1(); @Test public void testWampler2(); @Test public void testWampler3(); public void testWampler4(); @Test public void testLongly(); @Test public void testOneRedundantColumn(); @Test public void testThreeRedundantColumn(); @Test public void testPCorr(); @Test public void testHdiag(); @Test public void testHdiagConstant(); @Test public void testSubsetRegression();
87d07343480ffca3bc98fdbe693da56389998dcff51842d52222725f7935959e
[ "org.apache.commons.math3.stat.regression.MillerUpdatingRegressionTest::testRegressAirlineConstantExternal" ]
private final int nvars; private final double[] d; private final double[] rhs; private final double[] r; private final double[] tol; private final double[] rss; private final int[] vorder; private final double[] work_tolset; private long nobs = 0; private double sserr = 0.0; private boolean rss_set = false; private boolean tol_set = false; private final boolean[] lindep; private final double[] x_sing; private final double[] work_sing; private double sumy = 0.0; private double sumsqy = 0.0; private boolean hasIntercept; private final double epsilon;
@Test public void testRegressAirlineConstantExternal()
private final static double[][] airdata = { /*"I",*/new double[]{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6}, /*"T",*/ new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, /*"C",*/ new double[]{1140640, 1215690, 1309570, 1511530, 1676730, 1823740, 2022890, 2314760, 2639160, 3247620, 3787750, 3867750, 3996020, 4282880, 4748320, 569292, 640614, 777655, 999294, 1203970, 1358100, 1501350, 1709270, 2025400, 2548370, 3137740, 3557700, 3717740, 3962370, 4209390, 286298, 309290, 342056, 374595, 450037, 510412, 575347, 669331, 783799, 913883, 1041520, 1125800, 1096070, 1198930, 1170470, 145167, 170192, 247506, 309391, 354338, 373941, 420915, 474017, 532590, 676771, 880438, 1052020, 1193680, 1303390, 1436970, 91361, 95428, 98187, 115967, 138382, 156228, 183169, 210212, 274024, 356915, 432344, 524294, 530924, 581447, 610257, 68978, 74904, 83829, 98148, 118449, 133161, 145062, 170711, 199775, 276797, 381478, 506969, 633388, 804388, 1009500}, /*"Q",*/ new double[]{0.952757, 0.986757, 1.09198, 1.17578, 1.16017, 1.17376, 1.29051, 1.39067, 1.61273, 1.82544, 1.54604, 1.5279, 1.6602, 1.82231, 1.93646, 0.520635, 0.534627, 0.655192, 0.791575, 0.842945, 0.852892, 0.922843, 1, 1.19845, 1.34067, 1.32624, 1.24852, 1.25432, 1.37177, 1.38974, 0.262424, 0.266433, 0.306043, 0.325586, 0.345706, 0.367517, 0.409937, 0.448023, 0.539595, 0.539382, 0.467967, 0.450544, 0.468793, 0.494397, 0.493317, 0.086393, 0.09674, 0.1415, 0.169715, 0.173805, 0.164272, 0.170906, 0.17784, 0.192248, 0.242469, 0.256505, 0.249657, 0.273923, 0.371131, 0.421411, 0.051028, 0.052646, 0.056348, 0.066953, 0.070308, 0.073961, 0.084946, 0.095474, 0.119814, 0.150046, 0.144014, 0.1693, 0.172761, 0.18667, 0.213279, 0.037682, 0.039784, 0.044331, 0.050245, 0.055046, 0.052462, 0.056977, 0.06149, 0.069027, 0.092749, 0.11264, 0.154154, 0.186461, 0.246847, 0.304013}, /*"PF",*/ new double[]{106650, 110307, 110574, 121974, 196606, 265609, 263451, 316411, 384110, 569251, 871636, 997239, 938002, 859572, 823411, 103795, 111477, 118664, 114797, 215322, 281704, 304818, 348609, 374579, 544109, 853356, 1003200, 941977, 856533, 821361, 118788, 123798, 122882, 131274, 222037, 278721, 306564, 356073, 378311, 555267, 850322, 1015610, 954508, 886999, 844079, 114987, 120501, 121908, 127220, 209405, 263148, 316724, 363598, 389436, 547376, 850418, 1011170, 951934, 881323, 831374, 118222, 116223, 115853, 129372, 243266, 277930, 317273, 358794, 397667, 566672, 848393, 1005740, 958231, 872924, 844622, 117112, 119420, 116087, 122997, 194309, 307923, 323595, 363081, 386422, 564867, 874818, 1013170, 930477, 851676, 819476}, /*"LF",*/ new double[]{0.534487, 0.532328, 0.547736, 0.540846, 0.591167, 0.575417, 0.594495, 0.597409, 0.638522, 0.676287, 0.605735, 0.61436, 0.633366, 0.650117, 0.625603, 0.490851, 0.473449, 0.503013, 0.512501, 0.566782, 0.558133, 0.558799, 0.57207, 0.624763, 0.628706, 0.58915, 0.532612, 0.526652, 0.540163, 0.528775, 0.524334, 0.537185, 0.582119, 0.579489, 0.606592, 0.60727, 0.582425, 0.573972, 0.654256, 0.631055, 0.56924, 0.589682, 0.587953, 0.565388, 0.577078, 0.432066, 0.439669, 0.488932, 0.484181, 0.529925, 0.532723, 0.549067, 0.55714, 0.611377, 0.645319, 0.611734, 0.580884, 0.572047, 0.59457, 0.585525, 0.442875, 0.462473, 0.519118, 0.529331, 0.557797, 0.556181, 0.569327, 0.583465, 0.631818, 0.604723, 0.587921, 0.616159, 0.605868, 0.594688, 0.635545, 0.448539, 0.475889, 0.500562, 0.500344, 0.528897, 0.495361, 0.510342, 0.518296, 0.546723, 0.554276, 0.517766, 0.580049, 0.556024, 0.537791, 0.525775} };
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.linear.RealMatrix; import org.apache.commons.math3.stat.correlation.PearsonsCorrelation; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; /** * MillerUpdatingRegression tests. */ public class MillerUpdatingRegressionTest { public MillerUpdatingRegressionTest() { } /* This is the Greene Airline Cost data. * The data can be downloaded from http://www.indiana.edu/~statmath/stat/all/panel/airline.csv */ private final static double[][] airdata = { /*"I",*/new double[]{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6}, /*"T",*/ new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, /*"C",*/ new double[]{1140640, 1215690, 1309570, 1511530, 1676730, 1823740, 2022890, 2314760, 2639160, 3247620, 3787750, 3867750, 3996020, 4282880, 4748320, 569292, 640614, 777655, 999294, 1203970, 1358100, 1501350, 1709270, 2025400, 2548370, 3137740, 3557700, 3717740, 3962370, 4209390, 286298, 309290, 342056, 374595, 450037, 510412, 575347, 669331, 783799, 913883, 1041520, 1125800, 1096070, 1198930, 1170470, 145167, 170192, 247506, 309391, 354338, 373941, 420915, 474017, 532590, 676771, 880438, 1052020, 1193680, 1303390, 1436970, 91361, 95428, 98187, 115967, 138382, 156228, 183169, 210212, 274024, 356915, 432344, 524294, 530924, 581447, 610257, 68978, 74904, 83829, 98148, 118449, 133161, 145062, 170711, 199775, 276797, 381478, 506969, 633388, 804388, 1009500}, /*"Q",*/ new double[]{0.952757, 0.986757, 1.09198, 1.17578, 1.16017, 1.17376, 1.29051, 1.39067, 1.61273, 1.82544, 1.54604, 1.5279, 1.6602, 1.82231, 1.93646, 0.520635, 0.534627, 0.655192, 0.791575, 0.842945, 0.852892, 0.922843, 1, 1.19845, 1.34067, 1.32624, 1.24852, 1.25432, 1.37177, 1.38974, 0.262424, 0.266433, 0.306043, 0.325586, 0.345706, 0.367517, 0.409937, 0.448023, 0.539595, 0.539382, 0.467967, 0.450544, 0.468793, 0.494397, 0.493317, 0.086393, 0.09674, 0.1415, 0.169715, 0.173805, 0.164272, 0.170906, 0.17784, 0.192248, 0.242469, 0.256505, 0.249657, 0.273923, 0.371131, 0.421411, 0.051028, 0.052646, 0.056348, 0.066953, 0.070308, 0.073961, 0.084946, 0.095474, 0.119814, 0.150046, 0.144014, 0.1693, 0.172761, 0.18667, 0.213279, 0.037682, 0.039784, 0.044331, 0.050245, 0.055046, 0.052462, 0.056977, 0.06149, 0.069027, 0.092749, 0.11264, 0.154154, 0.186461, 0.246847, 0.304013}, /*"PF",*/ new double[]{106650, 110307, 110574, 121974, 196606, 265609, 263451, 316411, 384110, 569251, 871636, 997239, 938002, 859572, 823411, 103795, 111477, 118664, 114797, 215322, 281704, 304818, 348609, 374579, 544109, 853356, 1003200, 941977, 856533, 821361, 118788, 123798, 122882, 131274, 222037, 278721, 306564, 356073, 378311, 555267, 850322, 1015610, 954508, 886999, 844079, 114987, 120501, 121908, 127220, 209405, 263148, 316724, 363598, 389436, 547376, 850418, 1011170, 951934, 881323, 831374, 118222, 116223, 115853, 129372, 243266, 277930, 317273, 358794, 397667, 566672, 848393, 1005740, 958231, 872924, 844622, 117112, 119420, 116087, 122997, 194309, 307923, 323595, 363081, 386422, 564867, 874818, 1013170, 930477, 851676, 819476}, /*"LF",*/ new double[]{0.534487, 0.532328, 0.547736, 0.540846, 0.591167, 0.575417, 0.594495, 0.597409, 0.638522, 0.676287, 0.605735, 0.61436, 0.633366, 0.650117, 0.625603, 0.490851, 0.473449, 0.503013, 0.512501, 0.566782, 0.558133, 0.558799, 0.57207, 0.624763, 0.628706, 0.58915, 0.532612, 0.526652, 0.540163, 0.528775, 0.524334, 0.537185, 0.582119, 0.579489, 0.606592, 0.60727, 0.582425, 0.573972, 0.654256, 0.631055, 0.56924, 0.589682, 0.587953, 0.565388, 0.577078, 0.432066, 0.439669, 0.488932, 0.484181, 0.529925, 0.532723, 0.549067, 0.55714, 0.611377, 0.645319, 0.611734, 0.580884, 0.572047, 0.59457, 0.585525, 0.442875, 0.462473, 0.519118, 0.529331, 0.557797, 0.556181, 0.569327, 0.583465, 0.631818, 0.604723, 0.587921, 0.616159, 0.605868, 0.594688, 0.635545, 0.448539, 0.475889, 0.500562, 0.500344, 0.528897, 0.495361, 0.510342, 0.518296, 0.546723, 0.554276, 0.517766, 0.580049, 0.556024, 0.537791, 0.525775} }; /** * Test of hasIntercept method, of class MillerUpdatingRegression. */ @Test public void testHasIntercept() { MillerUpdatingRegression instance = new MillerUpdatingRegression(10, false); if (instance.hasIntercept()) { Assert.fail("Should not have intercept"); } instance = new MillerUpdatingRegression(10, true); if (!instance.hasIntercept()) { Assert.fail("Should have intercept"); } } /** * Test of getN method, of class MillerUpdatingRegression. */ @Test public void testAddObsGetNClear() { MillerUpdatingRegression instance = new MillerUpdatingRegression(3, true); double[][] xAll = new double[airdata[0].length][]; double[] y = new double[airdata[0].length]; for (int i = 0; i < airdata[0].length; i++) { xAll[i] = new double[3]; xAll[i][0] = Math.log(airdata[3][i]); xAll[i][1] = Math.log(airdata[4][i]); xAll[i][2] = airdata[5][i]; y[i] = Math.log(airdata[2][i]); } instance.addObservations(xAll, y); if (instance.getN() != xAll.length) { Assert.fail("Number of observations not correct in bulk addition"); } instance.clear(); for (int i = 0; i < xAll.length; i++) { instance.addObservation(xAll[i], y[i]); } if (instance.getN() != xAll.length) { Assert.fail("Number of observations not correct in drip addition"); } return; } @Test public void testNegativeTestAddObs() { MillerUpdatingRegression instance = new MillerUpdatingRegression(3, true); try { instance.addObservation(new double[]{1.0}, 0.0); Assert.fail("Should throw IllegalArgumentException"); } catch (IllegalArgumentException iae) { } catch (Exception e) { Assert.fail("Should throw IllegalArgumentException"); } try { instance.addObservation(new double[]{1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}, 0.0); Assert.fail("Should throw IllegalArgumentException"); } catch (IllegalArgumentException iae) { } catch (Exception e) { Assert.fail("Should throw IllegalArgumentException"); } try { instance.addObservation(new double[]{1.0, 1.0, 1.0}, 0.0); } catch (Exception e) { Assert.fail("Should throw IllegalArgumentException"); } //now we try it without an intercept instance = new MillerUpdatingRegression(3, false); try { instance.addObservation(new double[]{1.0}, 0.0); Assert.fail("Should throw IllegalArgumentException [NOINTERCEPT]"); } catch (IllegalArgumentException iae) { } catch (Exception e) { Assert.fail("Should throw IllegalArgumentException [NOINTERCEPT]"); } try { instance.addObservation(new double[]{1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}, 0.0); Assert.fail("Should throw IllegalArgumentException [NOINTERCEPT]"); } catch (IllegalArgumentException iae) { } catch (Exception e) { Assert.fail("Should throw IllegalArgumentException [NOINTERCEPT]"); } try { instance.addObservation(new double[]{1.0, 1.0, 1.0}, 0.0); } catch (Exception e) { Assert.fail("Should throw IllegalArgumentException [NOINTERCEPT]"); } } @Test public void testNegativeTestAddMultipleObs() { MillerUpdatingRegression instance = new MillerUpdatingRegression(3, true); try { double[][] tst = {{1.0, 1.0, 1.0}, {1.20, 2.0, 2.1}}; double[] y = {1.0}; instance.addObservations(tst, y); Assert.fail("Should throw IllegalArgumentException"); } catch (IllegalArgumentException iae) { } catch (Exception e) { Assert.fail("Should throw IllegalArgumentException"); } try { double[][] tst = {{1.0, 1.0, 1.0}, {1.20, 2.0, 2.1}}; double[] y = {1.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0}; instance.addObservations(tst, y); Assert.fail("Should throw IllegalArgumentException"); } catch (IllegalArgumentException iae) { } catch (Exception e) { Assert.fail("Should throw IllegalArgumentException"); } } /* Results can be found at http://www.indiana.edu/~statmath/stat/all/panel/panel4.html * This test concerns a known data set */ @Test public void testRegressAirlineConstantExternal() { MillerUpdatingRegression instance = new MillerUpdatingRegression(4, false); double[][] x = new double[airdata[0].length][]; double[] y = new double[airdata[0].length]; for (int i = 0; i < airdata[0].length; i++) { x[i] = new double[4]; x[i][0] = 1.0; x[i][1] = Math.log(airdata[3][i]); x[i][2] = Math.log(airdata[4][i]); x[i][3] = airdata[5][i]; y[i] = Math.log(airdata[2][i]); } instance.addObservations(x, y); try { RegressionResults result = instance.regress(); Assert.assertNotNull("The test case is a prototype.", result); TestUtils.assertEquals( new double[]{9.5169, 0.8827, 0.4540, -1.6275}, result.getParameterEstimates(), 1e-4); TestUtils.assertEquals( new double[]{.2292445, .0132545, .0203042, .345302}, result.getStdErrorOfEstimates(), 1.0e-4); TestUtils.assertEquals(0.01552839, result.getMeanSquareError(), 1.0e-8); } catch (Exception e) { Assert.fail("Should not throw exception but does"); } } @Test public void testRegressAirlineConstantInternal() { MillerUpdatingRegression instance = new MillerUpdatingRegression(3, true); double[][] x = new double[airdata[0].length][]; double[] y = new double[airdata[0].length]; for (int i = 0; i < airdata[0].length; i++) { x[i] = new double[3]; x[i][0] = Math.log(airdata[3][i]); x[i][1] = Math.log(airdata[4][i]); x[i][2] = airdata[5][i]; y[i] = Math.log(airdata[2][i]); } instance.addObservations(x, y); try { RegressionResults result = instance.regress(); Assert.assertNotNull("The test case is a prototype.", result); TestUtils.assertEquals( new double[]{9.5169, 0.8827, 0.4540, -1.6275}, result.getParameterEstimates(), 1e-4); TestUtils.assertEquals( new double[]{.2292445, .0132545, .0203042, .345302}, result.getStdErrorOfEstimates(), 1.0e-4); TestUtils.assertEquals(0.9883, result.getRSquared(), 1.0e-4); TestUtils.assertEquals(0.01552839, result.getMeanSquareError(), 1.0e-8); } catch (Exception e) { Assert.fail("Should not throw exception but does"); } } @Test public void testFilippelli() { double[] data = new double[]{ 0.8116, -6.860120914, 0.9072, -4.324130045, 0.9052, -4.358625055, 0.9039, -4.358426747, 0.8053, -6.955852379, 0.8377, -6.661145254, 0.8667, -6.355462942, 0.8809, -6.118102026, 0.7975, -7.115148017, 0.8162, -6.815308569, 0.8515, -6.519993057, 0.8766, -6.204119983, 0.8885, -5.853871964, 0.8859, -6.109523091, 0.8959, -5.79832982, 0.8913, -5.482672118, 0.8959, -5.171791386, 0.8971, -4.851705903, 0.9021, -4.517126416, 0.909, -4.143573228, 0.9139, -3.709075441, 0.9199, -3.499489089, 0.8692, -6.300769497, 0.8872, -5.953504836, 0.89, -5.642065153, 0.891, -5.031376979, 0.8977, -4.680685696, 0.9035, -4.329846955, 0.9078, -3.928486195, 0.7675, -8.56735134, 0.7705, -8.363211311, 0.7713, -8.107682739, 0.7736, -7.823908741, 0.7775, -7.522878745, 0.7841, -7.218819279, 0.7971, -6.920818754, 0.8329, -6.628932138, 0.8641, -6.323946875, 0.8804, -5.991399828, 0.7668, -8.781464495, 0.7633, -8.663140179, 0.7678, -8.473531488, 0.7697, -8.247337057, 0.77, -7.971428747, 0.7749, -7.676129393, 0.7796, -7.352812702, 0.7897, -7.072065318, 0.8131, -6.774174009, 0.8498, -6.478861916, 0.8741, -6.159517513, 0.8061, -6.835647144, 0.846, -6.53165267, 0.8751, -6.224098421, 0.8856, -5.910094889, 0.8919, -5.598599459, 0.8934, -5.290645224, 0.894, -4.974284616, 0.8957, -4.64454848, 0.9047, -4.290560426, 0.9129, -3.885055584, 0.9209, -3.408378962, 0.9219, -3.13200249, 0.7739, -8.726767166, 0.7681, -8.66695597, 0.7665, -8.511026475, 0.7703, -8.165388579, 0.7702, -7.886056648, 0.7761, -7.588043762, 0.7809, -7.283412422, 0.7961, -6.995678626, 0.8253, -6.691862621, 0.8602, -6.392544977, 0.8809, -6.067374056, 0.8301, -6.684029655, 0.8664, -6.378719832, 0.8834, -6.065855188, 0.8898, -5.752272167, 0.8964, -5.132414673, 0.8963, -4.811352704, 0.9074, -4.098269308, 0.9119, -3.66174277, 0.9228, -3.2644011 }; MillerUpdatingRegression model = new MillerUpdatingRegression(10, true); int off = 0; double[] tmp = new double[10]; int nobs = 82; for (int i = 0; i < nobs; i++) { tmp[0] = data[off + 1]; // tmp[1] = tmp[0] * tmp[0]; // tmp[2] = tmp[0] * tmp[1]; //^3 // tmp[3] = tmp[1] * tmp[1]; //^4 // tmp[4] = tmp[2] * tmp[1]; //^5 // tmp[5] = tmp[2] * tmp[2]; //^6 // tmp[6] = tmp[2] * tmp[3]; //^7 // tmp[7] = tmp[3] * tmp[3]; //^8 // tmp[8] = tmp[4] * tmp[3]; //^9 // tmp[9] = tmp[4] * tmp[4]; //^10 tmp[1] = tmp[0] * tmp[0]; tmp[2] = tmp[0] * tmp[1]; tmp[3] = tmp[0] * tmp[2]; tmp[4] = tmp[0] * tmp[3]; tmp[5] = tmp[0] * tmp[4]; tmp[6] = tmp[0] * tmp[5]; tmp[7] = tmp[0] * tmp[6]; tmp[8] = tmp[0] * tmp[7]; tmp[9] = tmp[0] * tmp[8]; model.addObservation(tmp, data[off]); off += 2; } RegressionResults result = model.regress(); double[] betaHat = result.getParameterEstimates(); TestUtils.assertEquals(betaHat, new double[]{ -1467.48961422980, -2772.17959193342, -2316.37108160893, -1127.97394098372, -354.478233703349, -75.1242017393757, -10.8753180355343, -1.06221498588947, -0.670191154593408E-01, -0.246781078275479E-02, -0.402962525080404E-04 }, 1E-5); // // double[] se = result.getStdErrorOfEstimates(); TestUtils.assertEquals(se, new double[]{ 298.084530995537, 559.779865474950, 466.477572127796, 227.204274477751, 71.6478660875927, 15.2897178747400, 2.23691159816033, 0.221624321934227, 0.142363763154724E-01, 0.535617408889821E-03, 0.896632837373868E-05 }, 1E-5); // TestUtils.assertEquals(0.996727416185620, result.getRSquared(), 1.0e-8); TestUtils.assertEquals(0.112091743968020E-04, result.getMeanSquareError(), 1.0e-10); TestUtils.assertEquals(0.795851382172941E-03, result.getErrorSumSquares(), 1.0e-10); } @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}; MillerUpdatingRegression model = new MillerUpdatingRegression(5, true); int off = 0; double[] tmp = new double[5]; int nobs = 21; for (int i = 0; i < nobs; i++) { tmp[0] = data[off + 1]; tmp[1] = tmp[0] * tmp[0]; tmp[2] = tmp[0] * tmp[1]; tmp[3] = tmp[0] * tmp[2]; tmp[4] = tmp[0] * tmp[3]; model.addObservation(tmp, data[off]); off += 2; } RegressionResults result = model.regress(); double[] betaHat = result.getParameterEstimates(); TestUtils.assertEquals(betaHat, new double[]{1.0, 1.0, 1.0, 1.0, 1.0, 1.0}, 1E-8); // // double[] se = result.getStdErrorOfEstimates(); TestUtils.assertEquals(se, new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, 1E-8); // TestUtils.assertEquals(1.0, result.getRSquared(), 1.0e-10); TestUtils.assertEquals(0, result.getMeanSquareError(), 1.0e-7); TestUtils.assertEquals(0.00, result.getErrorSumSquares(), 1.0e-6); return; } @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}; MillerUpdatingRegression model = new MillerUpdatingRegression(5, true); int off = 0; double[] tmp = new double[5]; int nobs = 21; for (int i = 0; i < nobs; i++) { tmp[0] = data[off + 1]; tmp[1] = tmp[0] * tmp[0]; tmp[2] = tmp[0] * tmp[1]; tmp[3] = tmp[0] * tmp[2]; tmp[4] = tmp[0] * tmp[3]; model.addObservation(tmp, data[off]); off += 2; } RegressionResults result = model.regress(); double[] betaHat = result.getParameterEstimates(); 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 = result.getStdErrorOfEstimates(); TestUtils.assertEquals(se, new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, 1E-8); // TestUtils.assertEquals(1.0, result.getRSquared(), 1.0e-10); TestUtils.assertEquals(0, result.getMeanSquareError(), 1.0e-7); TestUtils.assertEquals(0.00, result.getErrorSumSquares(), 1.0e-6); return; } @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}; MillerUpdatingRegression model = new MillerUpdatingRegression(5, true); int off = 0; double[] tmp = new double[5]; int nobs = 21; for (int i = 0; i < nobs; i++) { tmp[0] = data[off + 1]; tmp[1] = tmp[0] * tmp[0]; tmp[2] = tmp[0] * tmp[1]; tmp[3] = tmp[0] * tmp[2]; tmp[4] = tmp[0] * tmp[3]; model.addObservation(tmp, data[off]); off += 2; } RegressionResults result = model.regress(); double[] betaHat = result.getParameterEstimates(); TestUtils.assertEquals(betaHat, new double[]{1.0, 1.0, 1.0, 1.0, 1.0, 1.0}, 1E-8); // double[] se = result.getStdErrorOfEstimates(); TestUtils.assertEquals(se, new double[]{2152.32624678170, 2363.55173469681, 779.343524331583, 101.475507550350, 5.64566512170752, 0.112324854679312}, 1E-8); // TestUtils.assertEquals(.999995559025820, result.getRSquared(), 1.0e-10); TestUtils.assertEquals(5570284.53333333, result.getMeanSquareError(), 1.0e-7); TestUtils.assertEquals(83554268.0000000, result.getErrorSumSquares(), 1.0e-6); return; } //@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}; MillerUpdatingRegression model = new MillerUpdatingRegression(5, true); int off = 0; double[] tmp = new double[5]; int nobs = 21; for (int i = 0; i < nobs; i++) { tmp[0] = data[off + 1]; tmp[1] = tmp[0] * tmp[0]; tmp[2] = tmp[0] * tmp[1]; tmp[3] = tmp[0] * tmp[2]; tmp[4] = tmp[0] * tmp[3]; model.addObservation(tmp, data[off]); off += 2; } RegressionResults result = model.regress(); double[] betaHat = result.getParameterEstimates(); TestUtils.assertEquals(betaHat, new double[]{1.0, 1.0, 1.0, 1.0, 1.0, 1.0}, 1E-8); // // double[] se = result.getStdErrorOfEstimates(); TestUtils.assertEquals(se, new double[]{215232.624678170, 236355.173469681, 77934.3524331583, 10147.5507550350, 564.566512170752, 11.2324854679312}, 1E-8); // TestUtils.assertEquals(.957478440825662, result.getRSquared(), 1.0e-10); TestUtils.assertEquals(55702845333.3333, result.getMeanSquareError(), 1.0e-4); TestUtils.assertEquals(835542680000.000, result.getErrorSumSquares(), 1.0e-3); return; } /** * 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 MillerUpdatingRegression model = new MillerUpdatingRegression(6, true); int off = 0; double[] tmp = new double[6]; for (int i = 0; i < nobs; i++) { System.arraycopy(design, off + 1, tmp, 0, nvars); model.addObservation(tmp, design[off]); off += nvars + 1; } // Check expected beta values from NIST RegressionResults result = model.regress(); double[] betaHat = result.getParameterEstimates(); TestUtils.assertEquals(betaHat, new double[]{-3482258.63459582, 15.0618722713733, -0.358191792925910E-01, -2.02022980381683, -1.03322686717359, -0.511041056535807E-01, 1829.15146461355}, 1E-8); // // Check standard errors from NIST double[] errors = result.getStdErrorOfEstimates(); TestUtils.assertEquals(new double[]{890420.383607373, 84.9149257747669, 0.334910077722432E-01, 0.488399681651699, 0.214274163161675, 0.226073200069370, 455.478499142212}, errors, 1E-6); // // Check R-Square statistics against R TestUtils.assertEquals(0.995479004577296, result.getRSquared(), 1E-12); TestUtils.assertEquals(0.992465007628826, result.getAdjustedRSquared(), 1E-12); // // // // Estimate model without intercept model = new MillerUpdatingRegression(6, false); off = 0; for (int i = 0; i < nobs; i++) { System.arraycopy(design, off + 1, tmp, 0, nvars); model.addObservation(tmp, design[off]); off += nvars + 1; } // Check expected beta values from R result = model.regress(); betaHat = result.getParameterEstimates(); 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 = result.getStdErrorOfEstimates(); TestUtils.assertEquals(new double[]{129.54486693117232, 0.03016640003786, 0.41773654056612, 0.27899087467676, 0.32128496193363, 17.68948737819961}, errors, 1E-11); // // // Check R-Square statistics against R TestUtils.assertEquals(0.9999670130706, result.getRSquared(), 1E-12); TestUtils.assertEquals(0.999947220913, result.getAdjustedRSquared(), 1E-12); } // @Test // public void testRegressReorder() { // // System.out.println("testRegressReorder"); // MillerUpdatingRegression instance = new MillerUpdatingRegression(4, false); // double[][] x = new double[airdata[0].length][]; // double[] y = new double[airdata[0].length]; // for (int i = 0; i < airdata[0].length; i++) { // x[i] = new double[4]; // x[i][0] = 1.0; // x[i][1] = Math.log(airdata[3][i]); // x[i][2] = Math.log(airdata[4][i]); // x[i][3] = airdata[5][i]; // y[i] = Math.log(airdata[2][i]); // } // // instance.addObservations(x, y); // RegressionResults result = instance.regress(); // if (result == null) { // Assert.fail("Null result...."); // } // // instance.reorderRegressors(new int[]{3, 2}, 0); // RegressionResults resultInverse = instance.regress(); // // double[] beta = result.getParameterEstimates(); // double[] betar = resultInverse.getParameterEstimates(); // if (Math.abs(beta[0] - betar[0]) > 1.0e-14) { // Assert.fail("Parameters not correct after reorder (0,3)"); // } // if (Math.abs(beta[1] - betar[1]) > 1.0e-14) { // Assert.fail("Parameters not correct after reorder (1,2)"); // } // if (Math.abs(beta[2] - betar[2]) > 1.0e-14) { // Assert.fail("Parameters not correct after reorder (2,1)"); // } // if (Math.abs(beta[3] - betar[3]) > 1.0e-14) { // Assert.fail("Parameters not correct after reorder (3,0)"); // } // } @Test public void testOneRedundantColumn() { MillerUpdatingRegression instance = new MillerUpdatingRegression(4, false); MillerUpdatingRegression instance2 = new MillerUpdatingRegression(5, false); double[][] x = new double[airdata[0].length][]; double[][] x2 = new double[airdata[0].length][]; double[] y = new double[airdata[0].length]; for (int i = 0; i < airdata[0].length; i++) { x[i] = new double[4]; x2[i] = new double[5]; x[i][0] = 1.0; x[i][1] = Math.log(airdata[3][i]); x[i][2] = Math.log(airdata[4][i]); x[i][3] = airdata[5][i]; x2[i][0] = x[i][0]; x2[i][1] = x[i][1]; x2[i][2] = x[i][2]; x2[i][3] = x[i][3]; x2[i][4] = x[i][3]; y[i] = Math.log(airdata[2][i]); } instance.addObservations(x, y); RegressionResults result = instance.regress(); Assert.assertNotNull("Could not estimate initial regression", result); instance2.addObservations(x2, y); RegressionResults resultRedundant = instance2.regress(); Assert.assertNotNull("Could not estimate redundant regression", resultRedundant); double[] beta = result.getParameterEstimates(); double[] betar = resultRedundant.getParameterEstimates(); double[] se = result.getStdErrorOfEstimates(); double[] ser = resultRedundant.getStdErrorOfEstimates(); for (int i = 0; i < beta.length; i++) { if (Math.abs(beta[i] - betar[i]) > 1.0e-8) { Assert.fail("Parameters not correctly estimated"); } if (Math.abs(se[i] - ser[i]) > 1.0e-8) { Assert.fail("Standard errors not correctly estimated"); } for (int j = 0; j < i; j++) { if (Math.abs(result.getCovarianceOfParameters(i, j) - resultRedundant.getCovarianceOfParameters(i, j)) > 1.0e-8) { Assert.fail("Variance Covariance not correct"); } } } TestUtils.assertEquals(result.getAdjustedRSquared(), resultRedundant.getAdjustedRSquared(), 1.0e-8); TestUtils.assertEquals(result.getErrorSumSquares(), resultRedundant.getErrorSumSquares(), 1.0e-8); TestUtils.assertEquals(result.getMeanSquareError(), resultRedundant.getMeanSquareError(), 1.0e-8); TestUtils.assertEquals(result.getRSquared(), resultRedundant.getRSquared(), 1.0e-8); return; } @Test public void testThreeRedundantColumn() { MillerUpdatingRegression instance = new MillerUpdatingRegression(4, false); MillerUpdatingRegression instance2 = new MillerUpdatingRegression(7, false); double[][] x = new double[airdata[0].length][]; double[][] x2 = new double[airdata[0].length][]; double[] y = new double[airdata[0].length]; for (int i = 0; i < airdata[0].length; i++) { x[i] = new double[4]; x2[i] = new double[7]; x[i][0] = 1.0; x[i][1] = Math.log(airdata[3][i]); x[i][2] = Math.log(airdata[4][i]); x[i][3] = airdata[5][i]; x2[i][0] = x[i][0]; x2[i][1] = x[i][0]; x2[i][2] = x[i][1]; x2[i][3] = x[i][2]; x2[i][4] = x[i][1]; x2[i][5] = x[i][3]; x2[i][6] = x[i][2]; y[i] = Math.log(airdata[2][i]); } instance.addObservations(x, y); RegressionResults result = instance.regress(); Assert.assertNotNull("Could not estimate initial regression", result); instance2.addObservations(x2, y); RegressionResults resultRedundant = instance2.regress(); Assert.assertNotNull("Could not estimate redundant regression", resultRedundant); double[] beta = result.getParameterEstimates(); double[] betar = resultRedundant.getParameterEstimates(); double[] se = result.getStdErrorOfEstimates(); double[] ser = resultRedundant.getStdErrorOfEstimates(); if (Math.abs(beta[0] - betar[0]) > 1.0e-8) { Assert.fail("Parameters not correct after reorder (0,3)"); } if (Math.abs(beta[1] - betar[2]) > 1.0e-8) { Assert.fail("Parameters not correct after reorder (1,2)"); } if (Math.abs(beta[2] - betar[3]) > 1.0e-8) { Assert.fail("Parameters not correct after reorder (2,1)"); } if (Math.abs(beta[3] - betar[5]) > 1.0e-8) { Assert.fail("Parameters not correct after reorder (3,0)"); } if (Math.abs(se[0] - ser[0]) > 1.0e-8) { Assert.fail("Se not correct after reorder (0,3)"); } if (Math.abs(se[1] - ser[2]) > 1.0e-8) { Assert.fail("Se not correct after reorder (1,2)"); } if (Math.abs(se[2] - ser[3]) > 1.0e-8) { Assert.fail("Se not correct after reorder (2,1)"); } if (Math.abs(se[3] - ser[5]) > 1.0e-8) { Assert.fail("Se not correct after reorder (3,0)"); } if (Math.abs(result.getCovarianceOfParameters(0, 0) - resultRedundant.getCovarianceOfParameters(0, 0)) > 1.0e-8) { Assert.fail("VCV not correct after reorder (0,0)"); } if (Math.abs(result.getCovarianceOfParameters(0, 1) - resultRedundant.getCovarianceOfParameters(0, 2)) > 1.0e-8) { Assert.fail("VCV not correct after reorder (0,1)<->(0,2)"); } if (Math.abs(result.getCovarianceOfParameters(0, 2) - resultRedundant.getCovarianceOfParameters(0, 3)) > 1.0e-8) { Assert.fail("VCV not correct after reorder (0,2)<->(0,1)"); } if (Math.abs(result.getCovarianceOfParameters(0, 3) - resultRedundant.getCovarianceOfParameters(0, 5)) > 1.0e-8) { Assert.fail("VCV not correct after reorder (0,3)<->(0,3)"); } if (Math.abs(result.getCovarianceOfParameters(1, 0) - resultRedundant.getCovarianceOfParameters(2, 0)) > 1.0e-8) { Assert.fail("VCV not correct after reorder (1,0)<->(2,0)"); } if (Math.abs(result.getCovarianceOfParameters(1, 1) - resultRedundant.getCovarianceOfParameters(2, 2)) > 1.0e-8) { Assert.fail("VCV not correct (1,1)<->(2,1)"); } if (Math.abs(result.getCovarianceOfParameters(1, 2) - resultRedundant.getCovarianceOfParameters(2, 3)) > 1.0e-8) { Assert.fail("VCV not correct (1,2)<->(2,2)"); } if (Math.abs(result.getCovarianceOfParameters(2, 0) - resultRedundant.getCovarianceOfParameters(3, 0)) > 1.0e-8) { Assert.fail("VCV not correct (2,0)<->(1,0)"); } if (Math.abs(result.getCovarianceOfParameters(2, 1) - resultRedundant.getCovarianceOfParameters(3, 2)) > 1.0e-8) { Assert.fail("VCV not correct (2,1)<->(1,2)"); } if (Math.abs(result.getCovarianceOfParameters(3, 3) - resultRedundant.getCovarianceOfParameters(5, 5)) > 1.0e-8) { Assert.fail("VCV not correct (3,3)<->(3,2)"); } TestUtils.assertEquals(result.getAdjustedRSquared(), resultRedundant.getAdjustedRSquared(), 1.0e-8); TestUtils.assertEquals(result.getErrorSumSquares(), resultRedundant.getErrorSumSquares(), 1.0e-8); TestUtils.assertEquals(result.getMeanSquareError(), resultRedundant.getMeanSquareError(), 1.0e-8); TestUtils.assertEquals(result.getRSquared(), resultRedundant.getRSquared(), 1.0e-8); return; } @Test public void testPCorr() { MillerUpdatingRegression instance = new MillerUpdatingRegression(4, false); double[][] x = new double[airdata[0].length][]; double[] y = new double[airdata[0].length]; double[] cp = new double[10]; double[] yxcorr = new double[4]; double[] diag = new double[4]; double sumysq = 0.0; int off = 0; for (int i = 0; i < airdata[0].length; i++) { x[i] = new double[4]; x[i][0] = 1.0; x[i][1] = Math.log(airdata[3][i]); x[i][2] = Math.log(airdata[4][i]); x[i][3] = airdata[5][i]; y[i] = Math.log(airdata[2][i]); off = 0; for (int j = 0; j < 4; j++) { double tmp = x[i][j]; for (int k = 0; k <= j; k++, off++) { cp[off] += tmp * x[i][k]; } yxcorr[j] += tmp * y[i]; } sumysq += y[i] * y[i]; } PearsonsCorrelation pearson = new PearsonsCorrelation(x); RealMatrix corr = pearson.getCorrelationMatrix(); off = 0; for (int i = 0; i < 4; i++, off += (i + 1)) { diag[i] = FastMath.sqrt(cp[off]); } instance.addObservations(x, y); double[] pc = instance.getPartialCorrelations(0); int idx = 0; off = 0; int off2 = 6; for (int i = 0; i < 4; i++) { for (int j = 0; j < i; j++) { if (Math.abs(pc[idx] - cp[off] / (diag[i] * diag[j])) > 1.0e-8) { Assert.fail("Failed cross products... i = " + i + " j = " + j); } ++idx; ++off; } ++off; if (Math.abs(pc[i+off2] - yxcorr[ i] / (FastMath.sqrt(sumysq) * diag[i])) > 1.0e-8) { Assert.fail("Assert.failed cross product i = " + i + " y"); } } double[] pc2 = instance.getPartialCorrelations(1); idx = 0; for (int i = 1; i < 4; i++) { for (int j = 1; j < i; j++) { if (Math.abs(pc2[idx] - corr.getEntry(j, i)) > 1.0e-8) { Assert.fail("Failed cross products... i = " + i + " j = " + j); } ++idx; } } double[] pc3 = instance.getPartialCorrelations(2); if (pc3 == null) { Assert.fail("Should not be null"); } return; } @Test public void testHdiag() { MillerUpdatingRegression instance = new MillerUpdatingRegression(4, false); double[][] x = new double[airdata[0].length][]; double[] y = new double[airdata[0].length]; for (int i = 0; i < airdata[0].length; i++) { x[i] = new double[4]; x[i][0] = 1.0; x[i][1] = Math.log(airdata[3][i]); x[i][2] = Math.log(airdata[4][i]); x[i][3] = airdata[5][i]; y[i] = Math.log(airdata[2][i]); } instance.addObservations(x, y); OLSMultipleLinearRegression ols = new OLSMultipleLinearRegression(); ols.setNoIntercept(true); ols.newSampleData(y, x); RealMatrix rm = ols.calculateHat(); for (int i = 0; i < x.length; i++) { TestUtils.assertEquals(instance.getDiagonalOfHatMatrix(x[i]), rm.getEntry(i, i), 1.0e-8); } return; } @Test public void testHdiagConstant() { MillerUpdatingRegression instance = new MillerUpdatingRegression(3, true); double[][] x = new double[airdata[0].length][]; double[] y = new double[airdata[0].length]; for (int i = 0; i < airdata[0].length; i++) { x[i] = new double[3]; x[i][0] = Math.log(airdata[3][i]); x[i][1] = Math.log(airdata[4][i]); x[i][2] = airdata[5][i]; y[i] = Math.log(airdata[2][i]); } instance.addObservations(x, y); OLSMultipleLinearRegression ols = new OLSMultipleLinearRegression(); ols.setNoIntercept(false); ols.newSampleData(y, x); RealMatrix rm = ols.calculateHat(); for (int i = 0; i < x.length; i++) { TestUtils.assertEquals(instance.getDiagonalOfHatMatrix(x[i]), rm.getEntry(i, i), 1.0e-8); } return; } @Test public void testSubsetRegression() { MillerUpdatingRegression instance = new MillerUpdatingRegression(3, true); MillerUpdatingRegression redRegression = new MillerUpdatingRegression(2, true); double[][] x = new double[airdata[0].length][]; double[][] xReduced = new double[airdata[0].length][]; double[] y = new double[airdata[0].length]; for (int i = 0; i < airdata[0].length; i++) { x[i] = new double[3]; x[i][0] = Math.log(airdata[3][i]); x[i][1] = Math.log(airdata[4][i]); x[i][2] = airdata[5][i]; xReduced[i] = new double[2]; xReduced[i][0] = Math.log(airdata[3][i]); xReduced[i][1] = Math.log(airdata[4][i]); y[i] = Math.log(airdata[2][i]); } instance.addObservations(x, y); redRegression.addObservations(xReduced, y); RegressionResults resultsInstance = instance.regress( new int[]{0,1,2} ); RegressionResults resultsReduced = redRegression.regress(); TestUtils.assertEquals(resultsInstance.getParameterEstimates(), resultsReduced.getParameterEstimates(), 1.0e-12); TestUtils.assertEquals(resultsInstance.getStdErrorOfEstimates(), resultsReduced.getStdErrorOfEstimates(), 1.0e-12); } }
[ { "be_test_class_file": "org/apache/commons/math3/stat/regression/MillerUpdatingRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.MillerUpdatingRegression", "be_test_function_name": "addObservation", "be_test_function_signature": "([DD)V", "line_numbers": [ "170", "172", "175", "176", "178", "179", "180", "181", "183", "185" ], "method_line_rate": 0.5 }, { "be_test_class_file": "org/apache/commons/math3/stat/regression/MillerUpdatingRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.MillerUpdatingRegression", "be_test_function_name": "addObservations", "be_test_function_signature": "([[D[D)V", "line_numbers": [ "195", "196", "201", "202", "205", "206", "210", "211", "213" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "org/apache/commons/math3/stat/regression/MillerUpdatingRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.MillerUpdatingRegression", "be_test_function_name": "cov", "be_test_function_signature": "(I)[D", "line_numbers": [ "493", "494", "496", "497", "498", "499", "502", "503", "504", "505", "506", "509", "510", "511", "512", "513", "514", "515", "516", "517", "518", "520", "522", "523", "524", "526", "527", "529", "531", "535", "537" ], "method_line_rate": 0.9354838709677419 }, { "be_test_class_file": "org/apache/commons/math3/stat/regression/MillerUpdatingRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.MillerUpdatingRegression", "be_test_function_name": "include", "be_test_function_signature": "([DDD)V", "line_numbers": [ "230", "231", "232", "239", "240", "241", "242", "243", "244", "246", "248", "249", "250", "252", "253", "254", "255", "256", "257", "258", "259", "261", "262", "263", "265", "266", "267", "268", "269", "270", "272", "274", "276", "277", "278", "279", "281", "284", "285" ], "method_line_rate": 0.9487179487179487 }, { "be_test_class_file": "org/apache/commons/math3/stat/regression/MillerUpdatingRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.MillerUpdatingRegression", "be_test_function_name": "inverse", "be_test_function_signature": "([DI)V", "line_numbers": [ "548", "549", "550", "551", "552", "553", "554", "555", "556", "557", "558", "559", "560", "561", "562", "563", "565", "567", "568", "570", "571", "574" ], "method_line_rate": 0.9545454545454546 }, { "be_test_class_file": "org/apache/commons/math3/stat/regression/MillerUpdatingRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.MillerUpdatingRegression", "be_test_function_name": "regcf", "be_test_function_signature": "(I)[D", "line_numbers": [ "373", "374", "376", "377", "380", "381", "383", "384", "385", "386", "387", "388", "389", "391", "392", "393", "394", "395", "399", "400", "401", "402", "406" ], "method_line_rate": 0.6086956521739131 }, { "be_test_class_file": "org/apache/commons/math3/stat/regression/MillerUpdatingRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.MillerUpdatingRegression", "be_test_function_name": "regress", "be_test_function_signature": "()Lorg/apache/commons/math3/stat/regression/RegressionResults;", "line_numbers": [ "906" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/stat/regression/MillerUpdatingRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.MillerUpdatingRegression", "be_test_function_name": "regress", "be_test_function_signature": "(I)Lorg/apache/commons/math3/stat/regression/RegressionResults;", "line_numbers": [ "920", "921", "925", "926", "930", "931", "933", "935", "937", "939", "940", "941", "942", "946", "947", "948", "949", "950", "953", "954", "958", "959", "961", "962", "963", "964", "965", "966", "971", "975", "976", "977", "978", "979", "980", "982", "984", "987" ], "method_line_rate": 0.42105263157894735 }, { "be_test_class_file": "org/apache/commons/math3/stat/regression/MillerUpdatingRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.MillerUpdatingRegression", "be_test_function_name": "singcheck", "be_test_function_signature": "()V", "line_numbers": [ "415", "416", "418", "422", "423", "424", "425", "426", "428", "433", "434", "435", "436", "437", "438", "439", "440", "441", "443", "444", "445", "446", "447", "448", "449", "453" ], "method_line_rate": 0.4230769230769231 }, { "be_test_class_file": "org/apache/commons/math3/stat/regression/MillerUpdatingRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.MillerUpdatingRegression", "be_test_function_name": "smartAdd", "be_test_function_signature": "(DD)D", "line_numbers": [ "295", "296", "297", "298", "299", "300", "302", "304", "305", "306", "308" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/stat/regression/MillerUpdatingRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.MillerUpdatingRegression", "be_test_function_name": "ss", "be_test_function_signature": "()V", "line_numbers": [ "465", "466", "467", "468", "469", "471", "472" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/stat/regression/MillerUpdatingRegression.java", "be_test_class_name": "org.apache.commons.math3.stat.regression.MillerUpdatingRegression", "be_test_function_name": "tolset", "be_test_function_signature": "()V", "line_numbers": [ "343", "344", "345", "347", "348", "349", "350", "351", "352", "353", "355", "357", "358" ], "method_line_rate": 1 } ]
public class ComplexTest
@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); }
// 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_realPartZero` 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 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> */
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,197
testNthRoot_cornercase_thirdRoot_realPartZero
```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_realPartZero` 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 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> */
1,180
// 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_realPartZero` 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 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() {
/** * 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> */
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_realPartZero` 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 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() { ```
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);
88081ac74a9e422e3dbc1c46f743d270bd5c3bd50a181ce306ddf395a88a6e5a
[ "org.apache.commons.math3.complex.ComplexTest::testNthRoot_cornercase_thirdRoot_realPartZero" ]
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_realPartZero()
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 LoopingIteratorTest extends TestCase
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()); }
// // 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 `testLooping2` for the `LoopingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests whether a populated looping iterator works as designed. * @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();
95
testLooping2
```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 `testLooping2` for the `LoopingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests whether a populated looping iterator works as designed. * @throws Exception If something unexpected occurs. */
82
// // 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 `testLooping2` for the `LoopingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests whether a populated looping iterator works as designed. * @throws Exception If something unexpected occurs. */ public void testLooping2() throws Exception {
/** * Tests whether a populated looping iterator works as designed. * @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 `testLooping2` for the `LoopingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests whether a populated looping iterator works as designed. * @throws Exception If something unexpected occurs. */ public void testLooping2() 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;
88f47be3955b743ab59260320ad1f4dabe5ce9fe860a6ae2101b5cbadf0df813
[ "org.apache.commons.collections4.iterators.LoopingIteratorTest::testLooping2" ]
private final Collection<? extends E> collection; private Iterator<? extends E> iterator;
public void testLooping2() 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": "hasNext", "be_test_function_signature": "()Z", "line_numbers": [ "72" ], "method_line_rate": 1 }, { "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.8 }, { "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 } ]
public final class EmpiricalDistributionTest extends RealDistributionAbstractTest
@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); } }
// 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 `testDensityIntegrals` for the `EmpiricalDistribution` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * 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. */
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;
408
testDensityIntegrals
```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 `testDensityIntegrals` for the `EmpiricalDistribution` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * 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. */
386
// 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 `testDensityIntegrals` for the `EmpiricalDistribution` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * 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() {
/** * 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. */
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 `testDensityIntegrals` for the `EmpiricalDistribution` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * 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() { ```
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);
89d84023ad347df997774ab15386e2cf06ee1f17a7c2e19af7c96f4c5d3965ec
[ "org.apache.commons.math3.random.EmpiricalDistributionTest::testDensityIntegrals" ]
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;
@Override @Test public void testDensityIntegrals()
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": "cumulativeProbability", "be_test_function_signature": "(D)D", "line_numbers": [ "639", "640", "641", "642", "644", "645", "646", "647", "648", "649", "650", "651", "653" ], "method_line_rate": 0.9230769230769231 }, { "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": "density", "be_test_function_signature": "(D)D", "line_numbers": [ "617", "618", "620", "621", "622" ], "method_line_rate": 0.8 }, { "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": 0.9333333333333333 }, { "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": "getKernel", "be_test_function_signature": "(Lorg/apache/commons/math3/stat/descriptive/SummaryStatistics;)Lorg/apache/commons/math3/distribution/RealDistribution;", "line_numbers": [ "848" ], "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": "k", "be_test_function_signature": "(D)Lorg/apache/commons/math3/distribution/RealDistribution;", "line_numbers": [ "826", "827" ], "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": "kB", "be_test_function_signature": "(I)D", "line_numbers": [ "813", "814", "815" ], "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": "([D)V", "line_numbers": [ "229", "231", "233", "234", "236", "237", "238", "240" ], "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": "pB", "be_test_function_signature": "(I)D", "line_numbers": [ "790" ], "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": "pBminus", "be_test_function_signature": "(I)D", "line_numbers": [ "801" ], "method_line_rate": 1 } ]
public class SkippingIteratorTest<E> extends AbstractIteratorTest<E>
@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 */ } }
// // 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 `testRemoveLast` for the `SkippingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test removing the last element. Verify that the element is removed from * the underlying collection. */
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();
275
testRemoveLast
```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 `testRemoveLast` for the `SkippingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test removing the last element. Verify that the element is removed from * the underlying collection. */
249
// // 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 `testRemoveLast` for the `SkippingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test removing the last element. Verify that the element is removed from * the underlying collection. */ @Test public void testRemoveLast() {
/** * Test removing the last element. Verify that the element is removed from * the underlying collection. */
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 `testRemoveLast` for the `SkippingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test removing the last element. Verify that the element is removed from * the underlying collection. */ @Test public void testRemoveLast() { ```
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();
8a08abb0574008f5fa517d120b0b6a016762d66ffb6296283d9c7975e9f04d3d
[ "org.apache.commons.collections4.iterators.SkippingIteratorTest::testRemoveLast" ]
private final long offset; private long pos;
@Test public void testRemoveLast()
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.75 } ]
public class DatasetUtilitiesTests extends TestCase
public void testBug2849731_2() { XYIntervalSeriesCollection d = new XYIntervalSeriesCollection(); XYIntervalSeries s = new XYIntervalSeries("S1"); s.add(1.0, Double.NaN, Double.NaN, Double.NaN, 1.5, Double.NaN); d.addSeries(s); Range r = DatasetUtilities.iterateDomainBounds(d); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(1.0, r.getUpperBound(), EPSILON); s.add(1.0, 1.5, Double.NaN, Double.NaN, 1.5, Double.NaN); r = DatasetUtilities.iterateDomainBounds(d); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(1.5, r.getUpperBound(), EPSILON); s.add(1.0, Double.NaN, 0.5, Double.NaN, 1.5, Double.NaN); r = DatasetUtilities.iterateDomainBounds(d); assertEquals(0.5, r.getLowerBound(), EPSILON); assertEquals(1.5, r.getUpperBound(), EPSILON); }
// public static Range iterateRangeBounds(XYDataset dataset, // boolean includeInterval); // public static Range iterateToFindDomainBounds(XYDataset dataset, // List visibleSeriesKeys, boolean includeInterval); // public static Range iterateToFindRangeBounds(XYDataset dataset, // List visibleSeriesKeys, Range xRange, boolean includeInterval); // public static Number findMinimumDomainValue(XYDataset dataset); // public static Number findMaximumDomainValue(XYDataset dataset); // public static Number findMinimumRangeValue(CategoryDataset dataset); // public static Number findMinimumRangeValue(XYDataset dataset); // public static Number findMaximumRangeValue(CategoryDataset dataset); // public static Number findMaximumRangeValue(XYDataset dataset); // public static Range findStackedRangeBounds(CategoryDataset dataset); // public static Range findStackedRangeBounds(CategoryDataset dataset, // double base); // public static Range findStackedRangeBounds(CategoryDataset dataset, // KeyToGroupMap map); // public static Number findMinimumStackedRangeValue(CategoryDataset dataset); // public static Number findMaximumStackedRangeValue(CategoryDataset dataset); // public static Range findStackedRangeBounds(TableXYDataset dataset); // public static Range findStackedRangeBounds(TableXYDataset dataset, // double base); // public static double calculateStackTotal(TableXYDataset dataset, int item); // public static Range findCumulativeRangeBounds(CategoryDataset dataset); // } // // // Abstract Java Test Class // package org.jfree.data.general.junit; // // import java.util.ArrayList; // import java.util.Arrays; // import java.util.Date; // import java.util.List; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.data.KeyToGroupMap; // import org.jfree.data.Range; // import org.jfree.data.category.CategoryDataset; // import org.jfree.data.category.DefaultCategoryDataset; // import org.jfree.data.category.DefaultIntervalCategoryDataset; // import org.jfree.data.function.Function2D; // import org.jfree.data.function.LineFunction2D; // import org.jfree.data.general.DatasetUtilities; // import org.jfree.data.pie.DefaultPieDataset; // import org.jfree.data.pie.PieDataset; // import org.jfree.data.statistics.BoxAndWhiskerItem; // import org.jfree.data.statistics.DefaultBoxAndWhiskerXYDataset; // import org.jfree.data.statistics.DefaultMultiValueCategoryDataset; // import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; // import org.jfree.data.statistics.MultiValueCategoryDataset; // import org.jfree.data.xy.DefaultIntervalXYDataset; // import org.jfree.data.xy.DefaultTableXYDataset; // import org.jfree.data.xy.DefaultXYDataset; // import org.jfree.data.xy.IntervalXYDataset; // import org.jfree.data.xy.TableXYDataset; // import org.jfree.data.xy.XYDataset; // import org.jfree.data.xy.XYIntervalSeries; // import org.jfree.data.xy.XYIntervalSeriesCollection; // import org.jfree.data.xy.XYSeries; // import org.jfree.data.xy.XYSeriesCollection; // import org.jfree.data.xy.YIntervalSeries; // import org.jfree.data.xy.YIntervalSeriesCollection; // // // // public class DatasetUtilitiesTests extends TestCase { // private static final double EPSILON = 0.0000000001; // // public static Test suite(); // public DatasetUtilitiesTests(String name); // public void testJava(); // public void testCalculatePieDatasetTotal(); // public void testFindDomainBounds(); // public void testFindDomainBounds2(); // public void testFindDomainBounds3(); // public void testFindDomainBounds_NaN(); // public void testIterateDomainBounds(); // public void testIterateDomainBounds_NaN(); // public void testIterateDomainBounds_NaN2(); // public void testFindRangeBounds_CategoryDataset(); // public void testFindRangeBounds(); // public void testFindRangeBounds2(); // public void testIterateRangeBounds_CategoryDataset(); // public void testIterateRangeBounds2_CategoryDataset(); // public void testIterateRangeBounds3_CategoryDataset(); // public void testIterateRangeBounds(); // public void testIterateRangeBounds2(); // public void testIterateRangeBounds3(); // public void testIterateRangeBounds4(); // public void testFindMinimumDomainValue(); // public void testFindMaximumDomainValue(); // public void testFindMinimumRangeValue(); // public void testFindMaximumRangeValue(); // public void testMinMaxRange(); // public void test803660(); // public void testCumulativeRange1(); // public void testCumulativeRange2(); // public void testCumulativeRange3(); // public void testCumulativeRange_NaN(); // public void testCreateCategoryDataset1(); // public void testCreateCategoryDataset2(); // public void testMaximumStackedRangeValue(); // public void testFindStackedRangeBounds_CategoryDataset1(); // public void testFindStackedRangeBounds_CategoryDataset2(); // public void testFindStackedRangeBounds_CategoryDataset3(); // public void testFindStackedRangeBoundsForTableXYDataset1(); // public void testFindStackedRangeBoundsForTableXYDataset2(); // public void testStackedRangeWithMap(); // public void testIsEmptyOrNullXYDataset(); // public void testLimitPieDataset(); // public void testSampleFunction2D(); // public void testFindMinimumStackedRangeValue(); // public void testFindMinimumStackedRangeValue2(); // public void testFindMaximumStackedRangeValue(); // public void testFindMaximumStackedRangeValue2(); // private CategoryDataset createCategoryDataset1(); // private CategoryDataset createCategoryDataset2(); // private XYDataset createXYDataset1(); // private TableXYDataset createTableXYDataset1(); // public void testIterateToFindRangeBounds1_XYDataset(); // public void testIterateToFindRangeBounds2_XYDataset(); // public void testIterateToFindRangeBounds_BoxAndWhiskerXYDataset(); // public void testIterateToFindRangeBounds_StatisticalCategoryDataset(); // public void testIterateToFindRangeBounds_MultiValueCategoryDataset(); // public void testIterateRangeBounds_IntervalCategoryDataset(); // public void testBug2849731(); // public void testBug2849731_2(); // public void testBug2849731_3(); // } // You are a professional Java test case writer, please create a test case named `testBug2849731_2` for the `DatasetUtilities` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Another test for bug 2849731. */
tests/org/jfree/data/general/junit/DatasetUtilitiesTests.java
package org.jfree.data.general; import org.jfree.data.pie.PieDataset; import org.jfree.data.pie.DefaultPieDataset; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.jfree.chart.util.ArrayUtilities; import org.jfree.data.DomainInfo; import org.jfree.data.KeyToGroupMap; import org.jfree.data.KeyedValues; import org.jfree.data.Range; import org.jfree.data.RangeInfo; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.CategoryRangeInfo; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.category.IntervalCategoryDataset; import org.jfree.data.function.Function2D; import org.jfree.data.statistics.BoxAndWhiskerCategoryDataset; import org.jfree.data.statistics.BoxAndWhiskerXYDataset; import org.jfree.data.statistics.MultiValueCategoryDataset; import org.jfree.data.statistics.StatisticalCategoryDataset; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.OHLCDataset; import org.jfree.data.xy.TableXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYDomainInfo; import org.jfree.data.xy.XYRangeInfo; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection;
private DatasetUtilities(); public static double calculatePieDatasetTotal(PieDataset dataset); public static PieDataset createPieDatasetForRow(CategoryDataset dataset, Comparable rowKey); public static PieDataset createPieDatasetForRow(CategoryDataset dataset, int row); public static PieDataset createPieDatasetForColumn(CategoryDataset dataset, Comparable columnKey); public static PieDataset createPieDatasetForColumn(CategoryDataset dataset, int column); public static PieDataset createConsolidatedPieDataset(PieDataset source, Comparable key, double minimumPercent); public static PieDataset createConsolidatedPieDataset(PieDataset source, Comparable key, double minimumPercent, int minItems); public static CategoryDataset createCategoryDataset(String rowKeyPrefix, String columnKeyPrefix, double[][] data); public static CategoryDataset createCategoryDataset(String rowKeyPrefix, String columnKeyPrefix, Number[][] data); public static CategoryDataset createCategoryDataset(Comparable[] rowKeys, Comparable[] columnKeys, double[][] data); public static CategoryDataset createCategoryDataset(Comparable rowKey, KeyedValues rowData); public static XYDataset sampleFunction2D(Function2D f, double start, double end, int samples, Comparable seriesKey); public static XYSeries sampleFunction2DToSeries(Function2D f, double start, double end, int samples, Comparable seriesKey); public static boolean isEmptyOrNull(PieDataset dataset); public static boolean isEmptyOrNull(CategoryDataset dataset); public static boolean isEmptyOrNull(XYDataset dataset); public static Range findDomainBounds(XYDataset dataset); public static Range findDomainBounds(XYDataset dataset, boolean includeInterval); public static Range findDomainBounds(XYDataset dataset, List visibleSeriesKeys, boolean includeInterval); public static Range iterateDomainBounds(XYDataset dataset); public static Range iterateDomainBounds(XYDataset dataset, boolean includeInterval); public static Range findRangeBounds(CategoryDataset dataset); public static Range findRangeBounds(CategoryDataset dataset, boolean includeInterval); public static Range findRangeBounds(CategoryDataset dataset, List visibleSeriesKeys, boolean includeInterval); public static Range findRangeBounds(XYDataset dataset); public static Range findRangeBounds(XYDataset dataset, boolean includeInterval); public static Range findRangeBounds(XYDataset dataset, List visibleSeriesKeys, Range xRange, boolean includeInterval); public static Range iterateCategoryRangeBounds(CategoryDataset dataset, boolean includeInterval); public static Range iterateRangeBounds(CategoryDataset dataset); public static Range iterateRangeBounds(CategoryDataset dataset, boolean includeInterval); public static Range iterateToFindRangeBounds(CategoryDataset dataset, List visibleSeriesKeys, boolean includeInterval); public static Range iterateXYRangeBounds(XYDataset dataset); public static Range iterateRangeBounds(XYDataset dataset); public static Range iterateRangeBounds(XYDataset dataset, boolean includeInterval); public static Range iterateToFindDomainBounds(XYDataset dataset, List visibleSeriesKeys, boolean includeInterval); public static Range iterateToFindRangeBounds(XYDataset dataset, List visibleSeriesKeys, Range xRange, boolean includeInterval); public static Number findMinimumDomainValue(XYDataset dataset); public static Number findMaximumDomainValue(XYDataset dataset); public static Number findMinimumRangeValue(CategoryDataset dataset); public static Number findMinimumRangeValue(XYDataset dataset); public static Number findMaximumRangeValue(CategoryDataset dataset); public static Number findMaximumRangeValue(XYDataset dataset); public static Range findStackedRangeBounds(CategoryDataset dataset); public static Range findStackedRangeBounds(CategoryDataset dataset, double base); public static Range findStackedRangeBounds(CategoryDataset dataset, KeyToGroupMap map); public static Number findMinimumStackedRangeValue(CategoryDataset dataset); public static Number findMaximumStackedRangeValue(CategoryDataset dataset); public static Range findStackedRangeBounds(TableXYDataset dataset); public static Range findStackedRangeBounds(TableXYDataset dataset, double base); public static double calculateStackTotal(TableXYDataset dataset, int item); public static Range findCumulativeRangeBounds(CategoryDataset dataset);
1,287
testBug2849731_2
```java public static Range iterateRangeBounds(XYDataset dataset, boolean includeInterval); public static Range iterateToFindDomainBounds(XYDataset dataset, List visibleSeriesKeys, boolean includeInterval); public static Range iterateToFindRangeBounds(XYDataset dataset, List visibleSeriesKeys, Range xRange, boolean includeInterval); public static Number findMinimumDomainValue(XYDataset dataset); public static Number findMaximumDomainValue(XYDataset dataset); public static Number findMinimumRangeValue(CategoryDataset dataset); public static Number findMinimumRangeValue(XYDataset dataset); public static Number findMaximumRangeValue(CategoryDataset dataset); public static Number findMaximumRangeValue(XYDataset dataset); public static Range findStackedRangeBounds(CategoryDataset dataset); public static Range findStackedRangeBounds(CategoryDataset dataset, double base); public static Range findStackedRangeBounds(CategoryDataset dataset, KeyToGroupMap map); public static Number findMinimumStackedRangeValue(CategoryDataset dataset); public static Number findMaximumStackedRangeValue(CategoryDataset dataset); public static Range findStackedRangeBounds(TableXYDataset dataset); public static Range findStackedRangeBounds(TableXYDataset dataset, double base); public static double calculateStackTotal(TableXYDataset dataset, int item); public static Range findCumulativeRangeBounds(CategoryDataset dataset); } // Abstract Java Test Class package org.jfree.data.general.junit; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.KeyToGroupMap; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.category.DefaultIntervalCategoryDataset; import org.jfree.data.function.Function2D; import org.jfree.data.function.LineFunction2D; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.pie.DefaultPieDataset; import org.jfree.data.pie.PieDataset; import org.jfree.data.statistics.BoxAndWhiskerItem; import org.jfree.data.statistics.DefaultBoxAndWhiskerXYDataset; import org.jfree.data.statistics.DefaultMultiValueCategoryDataset; import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; import org.jfree.data.statistics.MultiValueCategoryDataset; import org.jfree.data.xy.DefaultIntervalXYDataset; import org.jfree.data.xy.DefaultTableXYDataset; import org.jfree.data.xy.DefaultXYDataset; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.TableXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYIntervalSeries; import org.jfree.data.xy.XYIntervalSeriesCollection; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.data.xy.YIntervalSeries; import org.jfree.data.xy.YIntervalSeriesCollection; public class DatasetUtilitiesTests extends TestCase { private static final double EPSILON = 0.0000000001; public static Test suite(); public DatasetUtilitiesTests(String name); public void testJava(); public void testCalculatePieDatasetTotal(); public void testFindDomainBounds(); public void testFindDomainBounds2(); public void testFindDomainBounds3(); public void testFindDomainBounds_NaN(); public void testIterateDomainBounds(); public void testIterateDomainBounds_NaN(); public void testIterateDomainBounds_NaN2(); public void testFindRangeBounds_CategoryDataset(); public void testFindRangeBounds(); public void testFindRangeBounds2(); public void testIterateRangeBounds_CategoryDataset(); public void testIterateRangeBounds2_CategoryDataset(); public void testIterateRangeBounds3_CategoryDataset(); public void testIterateRangeBounds(); public void testIterateRangeBounds2(); public void testIterateRangeBounds3(); public void testIterateRangeBounds4(); public void testFindMinimumDomainValue(); public void testFindMaximumDomainValue(); public void testFindMinimumRangeValue(); public void testFindMaximumRangeValue(); public void testMinMaxRange(); public void test803660(); public void testCumulativeRange1(); public void testCumulativeRange2(); public void testCumulativeRange3(); public void testCumulativeRange_NaN(); public void testCreateCategoryDataset1(); public void testCreateCategoryDataset2(); public void testMaximumStackedRangeValue(); public void testFindStackedRangeBounds_CategoryDataset1(); public void testFindStackedRangeBounds_CategoryDataset2(); public void testFindStackedRangeBounds_CategoryDataset3(); public void testFindStackedRangeBoundsForTableXYDataset1(); public void testFindStackedRangeBoundsForTableXYDataset2(); public void testStackedRangeWithMap(); public void testIsEmptyOrNullXYDataset(); public void testLimitPieDataset(); public void testSampleFunction2D(); public void testFindMinimumStackedRangeValue(); public void testFindMinimumStackedRangeValue2(); public void testFindMaximumStackedRangeValue(); public void testFindMaximumStackedRangeValue2(); private CategoryDataset createCategoryDataset1(); private CategoryDataset createCategoryDataset2(); private XYDataset createXYDataset1(); private TableXYDataset createTableXYDataset1(); public void testIterateToFindRangeBounds1_XYDataset(); public void testIterateToFindRangeBounds2_XYDataset(); public void testIterateToFindRangeBounds_BoxAndWhiskerXYDataset(); public void testIterateToFindRangeBounds_StatisticalCategoryDataset(); public void testIterateToFindRangeBounds_MultiValueCategoryDataset(); public void testIterateRangeBounds_IntervalCategoryDataset(); public void testBug2849731(); public void testBug2849731_2(); public void testBug2849731_3(); } ``` You are a professional Java test case writer, please create a test case named `testBug2849731_2` for the `DatasetUtilities` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Another test for bug 2849731. */
1,269
// public static Range iterateRangeBounds(XYDataset dataset, // boolean includeInterval); // public static Range iterateToFindDomainBounds(XYDataset dataset, // List visibleSeriesKeys, boolean includeInterval); // public static Range iterateToFindRangeBounds(XYDataset dataset, // List visibleSeriesKeys, Range xRange, boolean includeInterval); // public static Number findMinimumDomainValue(XYDataset dataset); // public static Number findMaximumDomainValue(XYDataset dataset); // public static Number findMinimumRangeValue(CategoryDataset dataset); // public static Number findMinimumRangeValue(XYDataset dataset); // public static Number findMaximumRangeValue(CategoryDataset dataset); // public static Number findMaximumRangeValue(XYDataset dataset); // public static Range findStackedRangeBounds(CategoryDataset dataset); // public static Range findStackedRangeBounds(CategoryDataset dataset, // double base); // public static Range findStackedRangeBounds(CategoryDataset dataset, // KeyToGroupMap map); // public static Number findMinimumStackedRangeValue(CategoryDataset dataset); // public static Number findMaximumStackedRangeValue(CategoryDataset dataset); // public static Range findStackedRangeBounds(TableXYDataset dataset); // public static Range findStackedRangeBounds(TableXYDataset dataset, // double base); // public static double calculateStackTotal(TableXYDataset dataset, int item); // public static Range findCumulativeRangeBounds(CategoryDataset dataset); // } // // // Abstract Java Test Class // package org.jfree.data.general.junit; // // import java.util.ArrayList; // import java.util.Arrays; // import java.util.Date; // import java.util.List; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.data.KeyToGroupMap; // import org.jfree.data.Range; // import org.jfree.data.category.CategoryDataset; // import org.jfree.data.category.DefaultCategoryDataset; // import org.jfree.data.category.DefaultIntervalCategoryDataset; // import org.jfree.data.function.Function2D; // import org.jfree.data.function.LineFunction2D; // import org.jfree.data.general.DatasetUtilities; // import org.jfree.data.pie.DefaultPieDataset; // import org.jfree.data.pie.PieDataset; // import org.jfree.data.statistics.BoxAndWhiskerItem; // import org.jfree.data.statistics.DefaultBoxAndWhiskerXYDataset; // import org.jfree.data.statistics.DefaultMultiValueCategoryDataset; // import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; // import org.jfree.data.statistics.MultiValueCategoryDataset; // import org.jfree.data.xy.DefaultIntervalXYDataset; // import org.jfree.data.xy.DefaultTableXYDataset; // import org.jfree.data.xy.DefaultXYDataset; // import org.jfree.data.xy.IntervalXYDataset; // import org.jfree.data.xy.TableXYDataset; // import org.jfree.data.xy.XYDataset; // import org.jfree.data.xy.XYIntervalSeries; // import org.jfree.data.xy.XYIntervalSeriesCollection; // import org.jfree.data.xy.XYSeries; // import org.jfree.data.xy.XYSeriesCollection; // import org.jfree.data.xy.YIntervalSeries; // import org.jfree.data.xy.YIntervalSeriesCollection; // // // // public class DatasetUtilitiesTests extends TestCase { // private static final double EPSILON = 0.0000000001; // // public static Test suite(); // public DatasetUtilitiesTests(String name); // public void testJava(); // public void testCalculatePieDatasetTotal(); // public void testFindDomainBounds(); // public void testFindDomainBounds2(); // public void testFindDomainBounds3(); // public void testFindDomainBounds_NaN(); // public void testIterateDomainBounds(); // public void testIterateDomainBounds_NaN(); // public void testIterateDomainBounds_NaN2(); // public void testFindRangeBounds_CategoryDataset(); // public void testFindRangeBounds(); // public void testFindRangeBounds2(); // public void testIterateRangeBounds_CategoryDataset(); // public void testIterateRangeBounds2_CategoryDataset(); // public void testIterateRangeBounds3_CategoryDataset(); // public void testIterateRangeBounds(); // public void testIterateRangeBounds2(); // public void testIterateRangeBounds3(); // public void testIterateRangeBounds4(); // public void testFindMinimumDomainValue(); // public void testFindMaximumDomainValue(); // public void testFindMinimumRangeValue(); // public void testFindMaximumRangeValue(); // public void testMinMaxRange(); // public void test803660(); // public void testCumulativeRange1(); // public void testCumulativeRange2(); // public void testCumulativeRange3(); // public void testCumulativeRange_NaN(); // public void testCreateCategoryDataset1(); // public void testCreateCategoryDataset2(); // public void testMaximumStackedRangeValue(); // public void testFindStackedRangeBounds_CategoryDataset1(); // public void testFindStackedRangeBounds_CategoryDataset2(); // public void testFindStackedRangeBounds_CategoryDataset3(); // public void testFindStackedRangeBoundsForTableXYDataset1(); // public void testFindStackedRangeBoundsForTableXYDataset2(); // public void testStackedRangeWithMap(); // public void testIsEmptyOrNullXYDataset(); // public void testLimitPieDataset(); // public void testSampleFunction2D(); // public void testFindMinimumStackedRangeValue(); // public void testFindMinimumStackedRangeValue2(); // public void testFindMaximumStackedRangeValue(); // public void testFindMaximumStackedRangeValue2(); // private CategoryDataset createCategoryDataset1(); // private CategoryDataset createCategoryDataset2(); // private XYDataset createXYDataset1(); // private TableXYDataset createTableXYDataset1(); // public void testIterateToFindRangeBounds1_XYDataset(); // public void testIterateToFindRangeBounds2_XYDataset(); // public void testIterateToFindRangeBounds_BoxAndWhiskerXYDataset(); // public void testIterateToFindRangeBounds_StatisticalCategoryDataset(); // public void testIterateToFindRangeBounds_MultiValueCategoryDataset(); // public void testIterateRangeBounds_IntervalCategoryDataset(); // public void testBug2849731(); // public void testBug2849731_2(); // public void testBug2849731_3(); // } // You are a professional Java test case writer, please create a test case named `testBug2849731_2` for the `DatasetUtilities` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Another test for bug 2849731. */ // } // DatasetUtilities.iterateRangeBounds(d)); // assertEquals(new Range(2.0, 4.0), // d.addItem(4.0, 0.0, 0.0, "R2", "C1"); // d.addItem(2.5, 2.0, 3.0, "R1", "C1"); // TestIntervalCategoryDataset d = new TestIntervalCategoryDataset(); // public void testBug2849731() { // Defects4J: flaky method public void testBug2849731_2() {
/** * Another test for bug 2849731. */ // } // DatasetUtilities.iterateRangeBounds(d)); // assertEquals(new Range(2.0, 4.0), // d.addItem(4.0, 0.0, 0.0, "R2", "C1"); // d.addItem(2.5, 2.0, 3.0, "R1", "C1"); // TestIntervalCategoryDataset d = new TestIntervalCategoryDataset(); // public void testBug2849731() { // Defects4J: flaky method
1
org.jfree.data.general.DatasetUtilities
tests
```java public static Range iterateRangeBounds(XYDataset dataset, boolean includeInterval); public static Range iterateToFindDomainBounds(XYDataset dataset, List visibleSeriesKeys, boolean includeInterval); public static Range iterateToFindRangeBounds(XYDataset dataset, List visibleSeriesKeys, Range xRange, boolean includeInterval); public static Number findMinimumDomainValue(XYDataset dataset); public static Number findMaximumDomainValue(XYDataset dataset); public static Number findMinimumRangeValue(CategoryDataset dataset); public static Number findMinimumRangeValue(XYDataset dataset); public static Number findMaximumRangeValue(CategoryDataset dataset); public static Number findMaximumRangeValue(XYDataset dataset); public static Range findStackedRangeBounds(CategoryDataset dataset); public static Range findStackedRangeBounds(CategoryDataset dataset, double base); public static Range findStackedRangeBounds(CategoryDataset dataset, KeyToGroupMap map); public static Number findMinimumStackedRangeValue(CategoryDataset dataset); public static Number findMaximumStackedRangeValue(CategoryDataset dataset); public static Range findStackedRangeBounds(TableXYDataset dataset); public static Range findStackedRangeBounds(TableXYDataset dataset, double base); public static double calculateStackTotal(TableXYDataset dataset, int item); public static Range findCumulativeRangeBounds(CategoryDataset dataset); } // Abstract Java Test Class package org.jfree.data.general.junit; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.KeyToGroupMap; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.category.DefaultIntervalCategoryDataset; import org.jfree.data.function.Function2D; import org.jfree.data.function.LineFunction2D; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.pie.DefaultPieDataset; import org.jfree.data.pie.PieDataset; import org.jfree.data.statistics.BoxAndWhiskerItem; import org.jfree.data.statistics.DefaultBoxAndWhiskerXYDataset; import org.jfree.data.statistics.DefaultMultiValueCategoryDataset; import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; import org.jfree.data.statistics.MultiValueCategoryDataset; import org.jfree.data.xy.DefaultIntervalXYDataset; import org.jfree.data.xy.DefaultTableXYDataset; import org.jfree.data.xy.DefaultXYDataset; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.TableXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYIntervalSeries; import org.jfree.data.xy.XYIntervalSeriesCollection; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.data.xy.YIntervalSeries; import org.jfree.data.xy.YIntervalSeriesCollection; public class DatasetUtilitiesTests extends TestCase { private static final double EPSILON = 0.0000000001; public static Test suite(); public DatasetUtilitiesTests(String name); public void testJava(); public void testCalculatePieDatasetTotal(); public void testFindDomainBounds(); public void testFindDomainBounds2(); public void testFindDomainBounds3(); public void testFindDomainBounds_NaN(); public void testIterateDomainBounds(); public void testIterateDomainBounds_NaN(); public void testIterateDomainBounds_NaN2(); public void testFindRangeBounds_CategoryDataset(); public void testFindRangeBounds(); public void testFindRangeBounds2(); public void testIterateRangeBounds_CategoryDataset(); public void testIterateRangeBounds2_CategoryDataset(); public void testIterateRangeBounds3_CategoryDataset(); public void testIterateRangeBounds(); public void testIterateRangeBounds2(); public void testIterateRangeBounds3(); public void testIterateRangeBounds4(); public void testFindMinimumDomainValue(); public void testFindMaximumDomainValue(); public void testFindMinimumRangeValue(); public void testFindMaximumRangeValue(); public void testMinMaxRange(); public void test803660(); public void testCumulativeRange1(); public void testCumulativeRange2(); public void testCumulativeRange3(); public void testCumulativeRange_NaN(); public void testCreateCategoryDataset1(); public void testCreateCategoryDataset2(); public void testMaximumStackedRangeValue(); public void testFindStackedRangeBounds_CategoryDataset1(); public void testFindStackedRangeBounds_CategoryDataset2(); public void testFindStackedRangeBounds_CategoryDataset3(); public void testFindStackedRangeBoundsForTableXYDataset1(); public void testFindStackedRangeBoundsForTableXYDataset2(); public void testStackedRangeWithMap(); public void testIsEmptyOrNullXYDataset(); public void testLimitPieDataset(); public void testSampleFunction2D(); public void testFindMinimumStackedRangeValue(); public void testFindMinimumStackedRangeValue2(); public void testFindMaximumStackedRangeValue(); public void testFindMaximumStackedRangeValue2(); private CategoryDataset createCategoryDataset1(); private CategoryDataset createCategoryDataset2(); private XYDataset createXYDataset1(); private TableXYDataset createTableXYDataset1(); public void testIterateToFindRangeBounds1_XYDataset(); public void testIterateToFindRangeBounds2_XYDataset(); public void testIterateToFindRangeBounds_BoxAndWhiskerXYDataset(); public void testIterateToFindRangeBounds_StatisticalCategoryDataset(); public void testIterateToFindRangeBounds_MultiValueCategoryDataset(); public void testIterateRangeBounds_IntervalCategoryDataset(); public void testBug2849731(); public void testBug2849731_2(); public void testBug2849731_3(); } ``` You are a professional Java test case writer, please create a test case named `testBug2849731_2` for the `DatasetUtilities` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Another test for bug 2849731. */ // } // DatasetUtilities.iterateRangeBounds(d)); // assertEquals(new Range(2.0, 4.0), // d.addItem(4.0, 0.0, 0.0, "R2", "C1"); // d.addItem(2.5, 2.0, 3.0, "R1", "C1"); // TestIntervalCategoryDataset d = new TestIntervalCategoryDataset(); // public void testBug2849731() { // Defects4J: flaky method public void testBug2849731_2() { ```
public final class DatasetUtilities
package org.jfree.data.general.junit; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.KeyToGroupMap; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.category.DefaultIntervalCategoryDataset; import org.jfree.data.function.Function2D; import org.jfree.data.function.LineFunction2D; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.pie.DefaultPieDataset; import org.jfree.data.pie.PieDataset; import org.jfree.data.statistics.BoxAndWhiskerItem; import org.jfree.data.statistics.DefaultBoxAndWhiskerXYDataset; import org.jfree.data.statistics.DefaultMultiValueCategoryDataset; import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; import org.jfree.data.statistics.MultiValueCategoryDataset; import org.jfree.data.xy.DefaultIntervalXYDataset; import org.jfree.data.xy.DefaultTableXYDataset; import org.jfree.data.xy.DefaultXYDataset; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.TableXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYIntervalSeries; import org.jfree.data.xy.XYIntervalSeriesCollection; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.data.xy.YIntervalSeries; import org.jfree.data.xy.YIntervalSeriesCollection;
public static Test suite(); public DatasetUtilitiesTests(String name); public void testJava(); public void testCalculatePieDatasetTotal(); public void testFindDomainBounds(); public void testFindDomainBounds2(); public void testFindDomainBounds3(); public void testFindDomainBounds_NaN(); public void testIterateDomainBounds(); public void testIterateDomainBounds_NaN(); public void testIterateDomainBounds_NaN2(); public void testFindRangeBounds_CategoryDataset(); public void testFindRangeBounds(); public void testFindRangeBounds2(); public void testIterateRangeBounds_CategoryDataset(); public void testIterateRangeBounds2_CategoryDataset(); public void testIterateRangeBounds3_CategoryDataset(); public void testIterateRangeBounds(); public void testIterateRangeBounds2(); public void testIterateRangeBounds3(); public void testIterateRangeBounds4(); public void testFindMinimumDomainValue(); public void testFindMaximumDomainValue(); public void testFindMinimumRangeValue(); public void testFindMaximumRangeValue(); public void testMinMaxRange(); public void test803660(); public void testCumulativeRange1(); public void testCumulativeRange2(); public void testCumulativeRange3(); public void testCumulativeRange_NaN(); public void testCreateCategoryDataset1(); public void testCreateCategoryDataset2(); public void testMaximumStackedRangeValue(); public void testFindStackedRangeBounds_CategoryDataset1(); public void testFindStackedRangeBounds_CategoryDataset2(); public void testFindStackedRangeBounds_CategoryDataset3(); public void testFindStackedRangeBoundsForTableXYDataset1(); public void testFindStackedRangeBoundsForTableXYDataset2(); public void testStackedRangeWithMap(); public void testIsEmptyOrNullXYDataset(); public void testLimitPieDataset(); public void testSampleFunction2D(); public void testFindMinimumStackedRangeValue(); public void testFindMinimumStackedRangeValue2(); public void testFindMaximumStackedRangeValue(); public void testFindMaximumStackedRangeValue2(); private CategoryDataset createCategoryDataset1(); private CategoryDataset createCategoryDataset2(); private XYDataset createXYDataset1(); private TableXYDataset createTableXYDataset1(); public void testIterateToFindRangeBounds1_XYDataset(); public void testIterateToFindRangeBounds2_XYDataset(); public void testIterateToFindRangeBounds_BoxAndWhiskerXYDataset(); public void testIterateToFindRangeBounds_StatisticalCategoryDataset(); public void testIterateToFindRangeBounds_MultiValueCategoryDataset(); public void testIterateRangeBounds_IntervalCategoryDataset(); public void testBug2849731(); public void testBug2849731_2(); public void testBug2849731_3();
8bab93c095240f70ef535e3a25901d7efccad29613c19abb9bfd1aa3d7a33dba
[ "org.jfree.data.general.junit.DatasetUtilitiesTests::testBug2849731_2" ]
public void testBug2849731_2()
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.] * * -------------------------- * DatasetUtilitiesTests.java * -------------------------- * (C) Copyright 2003-2009, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 18-Sep-2003 : Version 1 (DG); * 23-Mar-2004 : Added test for maximumStackedRangeValue() method (DG); * 04-Oct-2004 : Eliminated NumberUtils usage (DG); * 07-Jan-2005 : Updated for method name changes (DG); * 03-Feb-2005 : Added testFindStackedRangeBounds2() method (DG); * 26-Sep-2007 : Added testIsEmptyOrNullXYDataset() method (DG); * 28-Mar-2008 : Added and renamed various tests (DG); * 08-Oct-2008 : New tests to support patch 2131001 and related * changes (DG); * 25-Mar-2009 : Added tests for new iterateToFindRangeBounds() method (DG); * 16-May-2009 : Added * testIterateToFindRangeBounds_MultiValueCategoryDataset() (DG); * 10-Sep-2009 : Added tests for bug 2849731 (DG); * */ package org.jfree.data.general.junit; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.KeyToGroupMap; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.category.DefaultIntervalCategoryDataset; import org.jfree.data.function.Function2D; import org.jfree.data.function.LineFunction2D; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.pie.DefaultPieDataset; import org.jfree.data.pie.PieDataset; import org.jfree.data.statistics.BoxAndWhiskerItem; import org.jfree.data.statistics.DefaultBoxAndWhiskerXYDataset; import org.jfree.data.statistics.DefaultMultiValueCategoryDataset; import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; import org.jfree.data.statistics.MultiValueCategoryDataset; import org.jfree.data.xy.DefaultIntervalXYDataset; import org.jfree.data.xy.DefaultTableXYDataset; import org.jfree.data.xy.DefaultXYDataset; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.TableXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYIntervalSeries; import org.jfree.data.xy.XYIntervalSeriesCollection; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.data.xy.YIntervalSeries; import org.jfree.data.xy.YIntervalSeriesCollection; /** * Tests for the {@link DatasetUtilities} class. */ public class DatasetUtilitiesTests extends TestCase { private static final double EPSILON = 0.0000000001; /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(DatasetUtilitiesTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public DatasetUtilitiesTests(String name) { super(name); } /** * Some tests to verify that Java does what I think it does! */ public void testJava() { assertTrue(Double.isNaN(Math.min(1.0, Double.NaN))); assertTrue(Double.isNaN(Math.max(1.0, Double.NaN))); } /** * Some tests for the calculatePieDatasetTotal() method. */ public void testCalculatePieDatasetTotal() { DefaultPieDataset d = new DefaultPieDataset(); assertEquals(0.0, DatasetUtilities.calculatePieDatasetTotal(d), EPSILON); d.setValue("A", 1.0); assertEquals(1.0, DatasetUtilities.calculatePieDatasetTotal(d), EPSILON); d.setValue("B", 3.0); assertEquals(4.0, DatasetUtilities.calculatePieDatasetTotal(d), EPSILON); } /** * Some tests for the findDomainBounds() method. */ public void testFindDomainBounds() { XYDataset dataset = createXYDataset1(); Range r = DatasetUtilities.findDomainBounds(dataset); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(3.0, r.getUpperBound(), EPSILON); } /** * This test checks that the standard method has 'includeInterval' * defaulting to true. */ public void testFindDomainBounds2() { DefaultIntervalXYDataset dataset = new DefaultIntervalXYDataset(); double[] x1 = new double[] {1.0, 2.0, 3.0}; double[] x1Start = new double[] {0.9, 1.9, 2.9}; double[] x1End = new double[] {1.1, 2.1, 3.1}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[] y1Start = new double[] {1.09, 2.09, 3.09}; double[] y1End = new double[] {1.11, 2.11, 3.11}; double[][] data1 = new double[][] {x1, x1Start, x1End, y1, y1Start, y1End}; dataset.addSeries("S1", data1); Range r = DatasetUtilities.findDomainBounds(dataset); assertEquals(0.9, r.getLowerBound(), EPSILON); assertEquals(3.1, r.getUpperBound(), EPSILON); } /** * This test checks that when the 'includeInterval' flag is false, the * bounds come from the regular x-values. */ public void testFindDomainBounds3() { DefaultIntervalXYDataset dataset = new DefaultIntervalXYDataset(); double[] x1 = new double[] {1.0, 2.0, 3.0}; double[] x1Start = new double[] {0.9, 1.9, 2.9}; double[] x1End = new double[] {1.1, 2.1, 3.1}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[] y1Start = new double[] {1.09, 2.09, 3.09}; double[] y1End = new double[] {1.11, 2.11, 3.11}; double[][] data1 = new double[][] {x1, x1Start, x1End, y1, y1Start, y1End}; dataset.addSeries("S1", data1); Range r = DatasetUtilities.findDomainBounds(dataset, false); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(3.0, r.getUpperBound(), EPSILON); } /** * This test checks that NaN values are ignored. */ public void testFindDomainBounds_NaN() { DefaultIntervalXYDataset dataset = new DefaultIntervalXYDataset(); double[] x1 = new double[] {1.0, 2.0, Double.NaN}; double[] x1Start = new double[] {0.9, 1.9, Double.NaN}; double[] x1End = new double[] {1.1, 2.1, Double.NaN}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[] y1Start = new double[] {1.09, 2.09, 3.09}; double[] y1End = new double[] {1.11, 2.11, 3.11}; double[][] data1 = new double[][] {x1, x1Start, x1End, y1, y1Start, y1End}; dataset.addSeries("S1", data1); Range r = DatasetUtilities.findDomainBounds(dataset); assertEquals(0.9, r.getLowerBound(), EPSILON); assertEquals(2.1, r.getUpperBound(), EPSILON); r = DatasetUtilities.findDomainBounds(dataset, false); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(2.0, r.getUpperBound(), EPSILON); } /** * Some tests for the iterateDomainBounds() method. */ public void testIterateDomainBounds() { XYDataset dataset = createXYDataset1(); Range r = DatasetUtilities.iterateDomainBounds(dataset); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(3.0, r.getUpperBound(), EPSILON); } /** * Check that NaN values in the dataset are ignored. */ public void testIterateDomainBounds_NaN() { DefaultXYDataset dataset = new DefaultXYDataset(); double[] x = new double[] {1.0, 2.0, Double.NaN, 3.0}; double[] y = new double[] {9.0, 8.0, 7.0, 6.0}; dataset.addSeries("S1", new double[][] {x, y}); Range r = DatasetUtilities.iterateDomainBounds(dataset); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(3.0, r.getUpperBound(), EPSILON); } /** * Check that NaN values in the IntervalXYDataset are ignored. */ public void testIterateDomainBounds_NaN2() { DefaultIntervalXYDataset dataset = new DefaultIntervalXYDataset(); double[] x1 = new double[] {Double.NaN, 2.0, 3.0}; double[] x1Start = new double[] {0.9, Double.NaN, 2.9}; double[] x1End = new double[] {1.1, Double.NaN, 3.1}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[] y1Start = new double[] {1.09, 2.09, 3.09}; double[] y1End = new double[] {1.11, 2.11, 3.11}; double[][] data1 = new double[][] {x1, x1Start, x1End, y1, y1Start, y1End}; dataset.addSeries("S1", data1); Range r = DatasetUtilities.iterateDomainBounds(dataset, false); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(3.0, r.getUpperBound(), EPSILON); r = DatasetUtilities.iterateDomainBounds(dataset, true); assertEquals(0.9, r.getLowerBound(), EPSILON); assertEquals(3.1, r.getUpperBound(), EPSILON); } /** * Some tests for the findRangeBounds() for a CategoryDataset method. */ public void testFindRangeBounds_CategoryDataset() { CategoryDataset dataset = createCategoryDataset1(); Range r = DatasetUtilities.findRangeBounds(dataset); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(6.0, r.getUpperBound(), EPSILON); } /** * Some tests for the findRangeBounds() method on an XYDataset. */ public void testFindRangeBounds() { XYDataset dataset = createXYDataset1(); Range r = DatasetUtilities.findRangeBounds(dataset); assertEquals(100.0, r.getLowerBound(), EPSILON); assertEquals(105.0, r.getUpperBound(), EPSILON); } /** * A test for the findRangeBounds(XYDataset) method using * an IntervalXYDataset. */ public void testFindRangeBounds2() { YIntervalSeriesCollection dataset = new YIntervalSeriesCollection(); Range r = DatasetUtilities.findRangeBounds(dataset); assertNull(r); YIntervalSeries s1 = new YIntervalSeries("S1"); dataset.addSeries(s1); r = DatasetUtilities.findRangeBounds(dataset); assertNull(r); // try a single item s1.add(1.0, 2.0, 1.5, 2.5); r = DatasetUtilities.findRangeBounds(dataset); assertEquals(1.5, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); r = DatasetUtilities.findRangeBounds(dataset, false); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(2.0, r.getUpperBound(), EPSILON); // another item s1.add(2.0, 2.0, 1.4, 2.1); r = DatasetUtilities.findRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); // another empty series YIntervalSeries s2 = new YIntervalSeries("S2"); dataset.addSeries(s2); r = DatasetUtilities.findRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); // an item in series 2 s2.add(1.0, 2.0, 1.9, 2.6); r = DatasetUtilities.findRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.6, r.getUpperBound(), EPSILON); // what if we don't want the interval? r = DatasetUtilities.findRangeBounds(dataset, false); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(2.0, r.getUpperBound(), EPSILON); } /** * Some tests for the iterateRangeBounds() method. */ public void testIterateRangeBounds_CategoryDataset() { CategoryDataset dataset = createCategoryDataset1(); Range r = DatasetUtilities.iterateRangeBounds(dataset, false); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(6.0, r.getUpperBound(), EPSILON); } /** * Some checks for the iterateRangeBounds() method. */ public void testIterateRangeBounds2_CategoryDataset() { // an empty dataset should return a null range DefaultCategoryDataset dataset = new DefaultCategoryDataset(); Range r = DatasetUtilities.iterateRangeBounds(dataset, false); assertNull(r); // a dataset with a single value dataset.addValue(1.23, "R1", "C1"); r = DatasetUtilities.iterateRangeBounds(dataset, false); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); // null is ignored dataset.addValue(null, "R2", "C1"); r = DatasetUtilities.iterateRangeBounds(dataset, false); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); // a Double.NaN should be ignored dataset.addValue(Double.NaN, "R2", "C1"); r = DatasetUtilities.iterateRangeBounds(dataset, false); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); } /** * Some checks for the iterateRangeBounds() method using an * IntervalCategoryDataset. */ public void testIterateRangeBounds3_CategoryDataset() { Number[][] starts = new Double[2][3]; Number[][] ends = new Double[2][3]; starts[0][0] = new Double(1.0); starts[0][1] = new Double(2.0); starts[0][2] = new Double(3.0); starts[1][0] = new Double(11.0); starts[1][1] = new Double(12.0); starts[1][2] = new Double(13.0); ends[0][0] = new Double(4.0); ends[0][1] = new Double(5.0); ends[0][2] = new Double(6.0); ends[1][0] = new Double(16.0); ends[1][1] = new Double(15.0); ends[1][2] = new Double(14.0); DefaultIntervalCategoryDataset d = new DefaultIntervalCategoryDataset( starts, ends); Range r = DatasetUtilities.iterateRangeBounds(d, false); assertEquals(4.0, r.getLowerBound(), EPSILON); assertEquals(16.0, r.getUpperBound(), EPSILON); r = DatasetUtilities.iterateRangeBounds(d, true); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(16.0, r.getUpperBound(), EPSILON); } /** * Some tests for the iterateRangeBounds() method. */ public void testIterateRangeBounds() { XYDataset dataset = createXYDataset1(); Range r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(100.0, r.getLowerBound(), EPSILON); assertEquals(105.0, r.getUpperBound(), EPSILON); } /** * Check the range returned when a series contains a null value. */ public void testIterateRangeBounds2() { XYSeries s1 = new XYSeries("S1"); s1.add(1.0, 1.1); s1.add(2.0, null); s1.add(3.0, 3.3); XYSeriesCollection dataset = new XYSeriesCollection(s1); Range r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.1, r.getLowerBound(), EPSILON); assertEquals(3.3, r.getUpperBound(), EPSILON); } /** * Some checks for the iterateRangeBounds() method. */ public void testIterateRangeBounds3() { // an empty dataset should return a null range XYSeriesCollection dataset = new XYSeriesCollection(); Range r = DatasetUtilities.iterateRangeBounds(dataset); assertNull(r); XYSeries s1 = new XYSeries("S1"); dataset.addSeries(s1); r = DatasetUtilities.iterateRangeBounds(dataset); assertNull(r); // a dataset with a single value s1.add(1.0, 1.23); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); // null is ignored s1.add(2.0, null); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); // Double.NaN DOESN'T mess things up s1.add(3.0, Double.NaN); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); } /** * Some checks for the range bounds of a dataset that implements the * {@link IntervalXYDataset} interface. */ public void testIterateRangeBounds4() { YIntervalSeriesCollection dataset = new YIntervalSeriesCollection(); Range r = DatasetUtilities.iterateRangeBounds(dataset); assertNull(r); YIntervalSeries s1 = new YIntervalSeries("S1"); dataset.addSeries(s1); r = DatasetUtilities.iterateRangeBounds(dataset); assertNull(r); // try a single item s1.add(1.0, 2.0, 1.5, 2.5); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.5, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); // another item s1.add(2.0, 2.0, 1.4, 2.1); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); // another empty series YIntervalSeries s2 = new YIntervalSeries("S2"); dataset.addSeries(s2); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); // an item in series 2 s2.add(1.0, 2.0, 1.9, 2.6); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.6, r.getUpperBound(), EPSILON); } /** * Some tests for the findMinimumDomainValue() method. */ public void testFindMinimumDomainValue() { XYDataset dataset = createXYDataset1(); Number minimum = DatasetUtilities.findMinimumDomainValue(dataset); assertEquals(new Double(1.0), minimum); } /** * Some tests for the findMaximumDomainValue() method. */ public void testFindMaximumDomainValue() { XYDataset dataset = createXYDataset1(); Number maximum = DatasetUtilities.findMaximumDomainValue(dataset); assertEquals(new Double(3.0), maximum); } /** * Some tests for the findMinimumRangeValue() method. */ public void testFindMinimumRangeValue() { CategoryDataset d1 = createCategoryDataset1(); Number min1 = DatasetUtilities.findMinimumRangeValue(d1); assertEquals(new Double(1.0), min1); XYDataset d2 = createXYDataset1(); Number min2 = DatasetUtilities.findMinimumRangeValue(d2); assertEquals(new Double(100.0), min2); } /** * Some tests for the findMaximumRangeValue() method. */ public void testFindMaximumRangeValue() { CategoryDataset d1 = createCategoryDataset1(); Number max1 = DatasetUtilities.findMaximumRangeValue(d1); assertEquals(new Double(6.0), max1); XYDataset dataset = createXYDataset1(); Number maximum = DatasetUtilities.findMaximumRangeValue(dataset); assertEquals(new Double(105.0), maximum); } /** * A quick test of the min and max range value methods. */ public void testMinMaxRange() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(100.0, "Series 1", "Type 1"); dataset.addValue(101.1, "Series 1", "Type 2"); Number min = DatasetUtilities.findMinimumRangeValue(dataset); assertTrue(min.doubleValue() < 100.1); Number max = DatasetUtilities.findMaximumRangeValue(dataset); assertTrue(max.doubleValue() > 101.0); } /** * A test to reproduce bug report 803660. */ public void test803660() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(100.0, "Series 1", "Type 1"); dataset.addValue(101.1, "Series 1", "Type 2"); Number n = DatasetUtilities.findMaximumRangeValue(dataset); assertTrue(n.doubleValue() > 101.0); } /** * A simple test for the cumulative range calculation. The sequence of * "cumulative" values are considered to be { 0.0, 10.0, 25.0, 18.0 } so * the range should be 0.0 -> 25.0. */ public void testCumulativeRange1() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(10.0, "Series 1", "Start"); dataset.addValue(15.0, "Series 1", "Delta 1"); dataset.addValue(-7.0, "Series 1", "Delta 2"); Range range = DatasetUtilities.findCumulativeRangeBounds(dataset); assertEquals(0.0, range.getLowerBound(), 0.00000001); assertEquals(25.0, range.getUpperBound(), 0.00000001); } /** * A further test for the cumulative range calculation. */ public void testCumulativeRange2() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(-21.4, "Series 1", "Start Value"); dataset.addValue(11.57, "Series 1", "Delta 1"); dataset.addValue(3.51, "Series 1", "Delta 2"); dataset.addValue(-12.36, "Series 1", "Delta 3"); dataset.addValue(3.39, "Series 1", "Delta 4"); dataset.addValue(38.68, "Series 1", "Delta 5"); dataset.addValue(-43.31, "Series 1", "Delta 6"); dataset.addValue(-29.59, "Series 1", "Delta 7"); dataset.addValue(35.30, "Series 1", "Delta 8"); dataset.addValue(5.0, "Series 1", "Delta 9"); Range range = DatasetUtilities.findCumulativeRangeBounds(dataset); assertEquals(-49.51, range.getLowerBound(), 0.00000001); assertEquals(23.39, range.getUpperBound(), 0.00000001); } /** * A further test for the cumulative range calculation. */ public void testCumulativeRange3() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(15.76, "Product 1", "Labour"); dataset.addValue(8.66, "Product 1", "Administration"); dataset.addValue(4.71, "Product 1", "Marketing"); dataset.addValue(3.51, "Product 1", "Distribution"); dataset.addValue(32.64, "Product 1", "Total Expense"); Range range = DatasetUtilities.findCumulativeRangeBounds(dataset); assertEquals(0.0, range.getLowerBound(), EPSILON); assertEquals(65.28, range.getUpperBound(), EPSILON); } /** * Check that the findCumulativeRangeBounds() method ignores Double.NaN * values. */ public void testCumulativeRange_NaN() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(10.0, "Series 1", "Start"); dataset.addValue(15.0, "Series 1", "Delta 1"); dataset.addValue(Double.NaN, "Series 1", "Delta 2"); Range range = DatasetUtilities.findCumulativeRangeBounds(dataset); assertEquals(0.0, range.getLowerBound(), EPSILON); assertEquals(25.0, range.getUpperBound(), EPSILON); } /** * Test the creation of a dataset from an array. */ public void testCreateCategoryDataset1() { String[] rowKeys = {"R1", "R2", "R3"}; String[] columnKeys = {"C1", "C2"}; double[][] data = new double[3][]; data[0] = new double[] {1.1, 1.2}; data[1] = new double[] {2.1, 2.2}; data[2] = new double[] {3.1, 3.2}; CategoryDataset dataset = DatasetUtilities.createCategoryDataset( rowKeys, columnKeys, data); assertTrue(dataset.getRowCount() == 3); assertTrue(dataset.getColumnCount() == 2); } /** * Test the creation of a dataset from an array. This time is should fail * because the array dimensions are around the wrong way. */ public void testCreateCategoryDataset2() { boolean pass = false; String[] rowKeys = {"R1", "R2", "R3"}; String[] columnKeys = {"C1", "C2"}; double[][] data = new double[2][]; data[0] = new double[] {1.1, 1.2, 1.3}; data[1] = new double[] {2.1, 2.2, 2.3}; CategoryDataset dataset = null; try { dataset = DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, data); } catch (IllegalArgumentException e) { pass = true; // got it! } assertTrue(pass); assertTrue(dataset == null); } /** * Test for a bug reported in the forum: * * http://www.jfree.org/phpBB2/viewtopic.php?t=7903 */ public void testMaximumStackedRangeValue() { double v1 = 24.3; double v2 = 14.2; double v3 = 33.2; double v4 = 32.4; double v5 = 26.3; double v6 = 22.6; Number answer = new Double(Math.max(v1 + v2 + v3, v4 + v5 + v6)); DefaultCategoryDataset d = new DefaultCategoryDataset(); d.addValue(v1, "Row 0", "Column 0"); d.addValue(v2, "Row 1", "Column 0"); d.addValue(v3, "Row 2", "Column 0"); d.addValue(v4, "Row 0", "Column 1"); d.addValue(v5, "Row 1", "Column 1"); d.addValue(v6, "Row 2", "Column 1"); Number max = DatasetUtilities.findMaximumStackedRangeValue(d); assertTrue(max.equals(answer)); } /** * Some checks for the findStackedRangeBounds() method. */ public void testFindStackedRangeBounds_CategoryDataset1() { CategoryDataset d1 = createCategoryDataset1(); Range r = DatasetUtilities.findStackedRangeBounds(d1); assertEquals(0.0, r.getLowerBound(), EPSILON); assertEquals(15.0, r.getUpperBound(), EPSILON); d1 = createCategoryDataset2(); r = DatasetUtilities.findStackedRangeBounds(d1); assertEquals(-2.0, r.getLowerBound(), EPSILON); assertEquals(2.0, r.getUpperBound(), EPSILON); } /** * Some checks for the findStackedRangeBounds() method. */ public void testFindStackedRangeBounds_CategoryDataset2() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); Range r = DatasetUtilities.findStackedRangeBounds(dataset); assertTrue(r == null); dataset.addValue(5.0, "R1", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, 3.0); assertEquals(3.0, r.getLowerBound(), EPSILON); assertEquals(8.0, r.getUpperBound(), EPSILON); dataset.addValue(-1.0, "R2", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, 3.0); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(8.0, r.getUpperBound(), EPSILON); dataset.addValue(null, "R3", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, 3.0); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(8.0, r.getUpperBound(), EPSILON); dataset.addValue(Double.NaN, "R4", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, 3.0); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(8.0, r.getUpperBound(), EPSILON); } /** * Some checks for the findStackedRangeBounds(CategoryDataset, * KeyToGroupMap) method. */ public void testFindStackedRangeBounds_CategoryDataset3() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); KeyToGroupMap map = new KeyToGroupMap("Group A"); Range r = DatasetUtilities.findStackedRangeBounds(dataset, map); assertTrue(r == null); dataset.addValue(1.0, "R1", "C1"); dataset.addValue(2.0, "R2", "C1"); dataset.addValue(3.0, "R3", "C1"); dataset.addValue(4.0, "R4", "C1"); map.mapKeyToGroup("R1", "Group A"); map.mapKeyToGroup("R2", "Group A"); map.mapKeyToGroup("R3", "Group B"); map.mapKeyToGroup("R4", "Group B"); r = DatasetUtilities.findStackedRangeBounds(dataset, map); assertEquals(0.0, r.getLowerBound(), EPSILON); assertEquals(7.0, r.getUpperBound(), EPSILON); dataset.addValue(null, "R5", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, map); assertEquals(0.0, r.getLowerBound(), EPSILON); assertEquals(7.0, r.getUpperBound(), EPSILON); dataset.addValue(Double.NaN, "R6", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, map); assertEquals(0.0, r.getLowerBound(), EPSILON); assertEquals(7.0, r.getUpperBound(), EPSILON); } /** * Some checks for the findStackedRangeBounds() method. */ public void testFindStackedRangeBoundsForTableXYDataset1() { TableXYDataset d2 = createTableXYDataset1(); Range r = DatasetUtilities.findStackedRangeBounds(d2); assertEquals(-2.0, r.getLowerBound(), EPSILON); assertEquals(2.0, r.getUpperBound(), EPSILON); } /** * Some checks for the findStackedRangeBounds() method. */ public void testFindStackedRangeBoundsForTableXYDataset2() { DefaultTableXYDataset d = new DefaultTableXYDataset(); Range r = DatasetUtilities.findStackedRangeBounds(d); assertEquals(r, new Range(0.0, 0.0)); } /** * Tests the stacked range extent calculation. */ public void testStackedRangeWithMap() { CategoryDataset d = createCategoryDataset1(); KeyToGroupMap map = new KeyToGroupMap("G0"); map.mapKeyToGroup("R2", "G1"); Range r = DatasetUtilities.findStackedRangeBounds(d, map); assertEquals(0.0, r.getLowerBound(), EPSILON); assertEquals(9.0, r.getUpperBound(), EPSILON); } /** * Some checks for the isEmptyOrNull(XYDataset) method. */ public void testIsEmptyOrNullXYDataset() { XYSeriesCollection dataset = null; assertTrue(DatasetUtilities.isEmptyOrNull(dataset)); dataset = new XYSeriesCollection(); assertTrue(DatasetUtilities.isEmptyOrNull(dataset)); XYSeries s1 = new XYSeries("S1"); dataset.addSeries(s1); assertTrue(DatasetUtilities.isEmptyOrNull(dataset)); s1.add(1.0, 2.0); assertFalse(DatasetUtilities.isEmptyOrNull(dataset)); s1.clear(); assertTrue(DatasetUtilities.isEmptyOrNull(dataset)); } /** * Some checks for the limitPieDataset() methods. */ public void testLimitPieDataset() { // check that empty dataset is handled OK DefaultPieDataset d1 = new DefaultPieDataset(); PieDataset d2 = DatasetUtilities.createConsolidatedPieDataset(d1, "Other", 0.05); assertEquals(0, d2.getItemCount()); // check that minItem limit is observed d1.setValue("Item 1", 1.0); d1.setValue("Item 2", 49.50); d1.setValue("Item 3", 49.50); d2 = DatasetUtilities.createConsolidatedPieDataset(d1, "Other", 0.05); assertEquals(3, d2.getItemCount()); assertEquals("Item 1", d2.getKey(0)); assertEquals("Item 2", d2.getKey(1)); assertEquals("Item 3", d2.getKey(2)); // check that minItem limit is observed d1.setValue("Item 4", 1.0); d2 = DatasetUtilities.createConsolidatedPieDataset(d1, "Other", 0.05, 2); // and that simple aggregation works assertEquals(3, d2.getItemCount()); assertEquals("Item 2", d2.getKey(0)); assertEquals("Item 3", d2.getKey(1)); assertEquals("Other", d2.getKey(2)); assertEquals(new Double(2.0), d2.getValue("Other")); } /** * Some checks for the sampleFunction2D() method. */ public void testSampleFunction2D() { Function2D f = new LineFunction2D(0, 1); XYDataset dataset = DatasetUtilities.sampleFunction2D(f, 0.0, 1.0, 2, "S1"); assertEquals(1, dataset.getSeriesCount()); assertEquals("S1", dataset.getSeriesKey(0)); assertEquals(2, dataset.getItemCount(0)); assertEquals(0.0, dataset.getXValue(0, 0), EPSILON); assertEquals(0.0, dataset.getYValue(0, 0), EPSILON); assertEquals(1.0, dataset.getXValue(0, 1), EPSILON); assertEquals(1.0, dataset.getYValue(0, 1), EPSILON); } /** * A simple check for the findMinimumStackedRangeValue() method. */ public void testFindMinimumStackedRangeValue() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); // an empty dataset should return a null max Number min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertNull(min); dataset.addValue(1.0, "R1", "C1"); min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(0.0, min.doubleValue(), EPSILON); dataset.addValue(2.0, "R2", "C1"); min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(0.0, min.doubleValue(), EPSILON); dataset.addValue(-3.0, "R3", "C1"); min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(-3.0, min.doubleValue(), EPSILON); dataset.addValue(Double.NaN, "R4", "C1"); min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(-3.0, min.doubleValue(), EPSILON); } /** * A simple check for the findMaximumStackedRangeValue() method. */ public void testFindMinimumStackedRangeValue2() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(-1.0, "R1", "C1"); Number min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(-1.0, min.doubleValue(), EPSILON); dataset.addValue(-2.0, "R2", "C1"); min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(-3.0, min.doubleValue(), EPSILON); } /** * A simple check for the findMaximumStackedRangeValue() method. */ public void testFindMaximumStackedRangeValue() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); // an empty dataset should return a null max Number max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertNull(max); dataset.addValue(1.0, "R1", "C1"); max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(1.0, max.doubleValue(), EPSILON); dataset.addValue(2.0, "R2", "C1"); max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(3.0, max.doubleValue(), EPSILON); dataset.addValue(-3.0, "R3", "C1"); max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(3.0, max.doubleValue(), EPSILON); dataset.addValue(Double.NaN, "R4", "C1"); max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(3.0, max.doubleValue(), EPSILON); } /** * A simple check for the findMaximumStackedRangeValue() method. */ public void testFindMaximumStackedRangeValue2() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(-1.0, "R1", "C1"); Number max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(0.0, max.doubleValue(), EPSILON); dataset.addValue(-2.0, "R2", "C1"); max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(0.0, max.doubleValue(), EPSILON); } /** * Creates a dataset for testing. * * @return A dataset. */ private CategoryDataset createCategoryDataset1() { DefaultCategoryDataset result = new DefaultCategoryDataset(); result.addValue(1.0, "R0", "C0"); result.addValue(1.0, "R1", "C0"); result.addValue(1.0, "R2", "C0"); result.addValue(4.0, "R0", "C1"); result.addValue(5.0, "R1", "C1"); result.addValue(6.0, "R2", "C1"); return result; } /** * Creates a dataset for testing. * * @return A dataset. */ private CategoryDataset createCategoryDataset2() { DefaultCategoryDataset result = new DefaultCategoryDataset(); result.addValue(1.0, "R0", "C0"); result.addValue(-2.0, "R1", "C0"); result.addValue(2.0, "R0", "C1"); result.addValue(-1.0, "R1", "C1"); return result; } /** * Creates a dataset for testing. * * @return A dataset. */ private XYDataset createXYDataset1() { XYSeries series1 = new XYSeries("S1"); series1.add(1.0, 100.0); series1.add(2.0, 101.0); series1.add(3.0, 102.0); XYSeries series2 = new XYSeries("S2"); series2.add(1.0, 103.0); series2.add(2.0, null); series2.add(3.0, 105.0); XYSeriesCollection result = new XYSeriesCollection(); result.addSeries(series1); result.addSeries(series2); result.setIntervalWidth(0.0); return result; } /** * Creates a sample dataset for testing purposes. * * @return A sample dataset. */ private TableXYDataset createTableXYDataset1() { DefaultTableXYDataset dataset = new DefaultTableXYDataset(); XYSeries s1 = new XYSeries("Series 1", true, false); s1.add(1.0, 1.0); s1.add(2.0, 2.0); dataset.addSeries(s1); XYSeries s2 = new XYSeries("Series 2", true, false); s2.add(1.0, -2.0); s2.add(2.0, -1.0); dataset.addSeries(s2); return dataset; } /** * Some checks for the iteratorToFindRangeBounds(XYDataset...) method. */ public void testIterateToFindRangeBounds1_XYDataset() { // null dataset throws IllegalArgumentException boolean pass = false; try { DatasetUtilities.iterateToFindRangeBounds(null, new ArrayList(), new Range(0.0, 1.0), true); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); // null list throws IllegalArgumentException pass = false; try { DatasetUtilities.iterateToFindRangeBounds(new XYSeriesCollection(), null, new Range(0.0, 1.0), true); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); // null range throws IllegalArgumentException pass = false; try { DatasetUtilities.iterateToFindRangeBounds(new XYSeriesCollection(), new ArrayList(), null, true); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); } /** * Some tests for the iterateToFindRangeBounds() method. */ public void testIterateToFindRangeBounds2_XYDataset() { List visibleSeriesKeys = new ArrayList(); Range xRange = new Range(0.0, 10.0); // empty dataset returns null XYSeriesCollection dataset = new XYSeriesCollection(); Range r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertNull(r); // add an empty series XYSeries s1 = new XYSeries("A"); dataset.addSeries(s1); visibleSeriesKeys.add("A"); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertNull(r); // check a null value s1.add(1.0, null); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertNull(r); // check a NaN s1.add(2.0, Double.NaN); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertNull(r); // check a regular value s1.add(3.0, 5.0); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 5.0), r); // check another regular value s1.add(4.0, 6.0); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 6.0), r); // add a second series XYSeries s2 = new XYSeries("B"); dataset.addSeries(s2); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 6.0), r); visibleSeriesKeys.add("B"); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 6.0), r); // add a value to the second series s2.add(5.0, 15.0); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 15.0), r); // add a value that isn't in the xRange s2.add(15.0, 150.0); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 15.0), r); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, new Range(0.0, 20.0), false); assertEquals(new Range(5.0, 150.0), r); } /** * Some checks for the iterateToFindRangeBounds() method when applied to * a BoxAndWhiskerXYDataset. */ public void testIterateToFindRangeBounds_BoxAndWhiskerXYDataset() { DefaultBoxAndWhiskerXYDataset dataset = new DefaultBoxAndWhiskerXYDataset("Series 1"); List visibleSeriesKeys = new ArrayList(); visibleSeriesKeys.add("Series 1"); Range xRange = new Range(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); assertNull(DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false)); dataset.add(new Date(50L), new BoxAndWhiskerItem(5.0, 4.9, 2.0, 8.0, 1.0, 9.0, 0.0, 10.0, new ArrayList())); assertEquals(new Range(5.0, 5.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false)); assertEquals(new Range(1.0, 9.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, true)); } /** * Some checks for the iterateToFindRangeBounds(CategoryDataset...) * method. */ public void testIterateToFindRangeBounds_StatisticalCategoryDataset() { DefaultStatisticalCategoryDataset dataset = new DefaultStatisticalCategoryDataset(); List visibleSeriesKeys = new ArrayList(); assertNull(DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, false)); dataset.add(1.0, 0.5, "R1", "C1"); visibleSeriesKeys.add("R1"); assertEquals(new Range(1.0, 1.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, false)); assertEquals(new Range(0.5, 1.5), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); } /** * Some checks for the iterateToFindRangeBounds(CategoryDataset...) method * with a {@link MultiValueCategoryDataset}. */ public void testIterateToFindRangeBounds_MultiValueCategoryDataset() { DefaultMultiValueCategoryDataset dataset = new DefaultMultiValueCategoryDataset(); List visibleSeriesKeys = new ArrayList(); assertNull(DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); List values = Arrays.asList(new Double[] {new Double(1.0)}); dataset.add(values, "R1", "C1"); visibleSeriesKeys.add("R1"); assertEquals(new Range(1.0, 1.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); values = Arrays.asList(new Double[] {new Double(2.0), new Double(3.0)}); dataset.add(values, "R1", "C2"); assertEquals(new Range(1.0, 3.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); values = Arrays.asList(new Double[] {new Double(-1.0), new Double(-2.0)}); dataset.add(values, "R2", "C1"); assertEquals(new Range(1.0, 3.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); visibleSeriesKeys.add("R2"); assertEquals(new Range(-2.0, 3.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); } /** * Some checks for the iterateRangeBounds() method when passed an * IntervalCategoryDataset. */ public void testIterateRangeBounds_IntervalCategoryDataset() {} // Defects4J: flaky method // public void testIterateRangeBounds_IntervalCategoryDataset() { // TestIntervalCategoryDataset d = new TestIntervalCategoryDataset(); // d.addItem(1.0, 2.0, 3.0, "R1", "C1"); // assertEquals(new Range(1.0, 3.0), // DatasetUtilities.iterateRangeBounds(d)); // // d = new TestIntervalCategoryDataset(); // d.addItem(2.5, 2.0, 3.0, "R1", "C1"); // assertEquals(new Range(2.0, 3.0), // DatasetUtilities.iterateRangeBounds(d)); // // d = new TestIntervalCategoryDataset(); // d.addItem(4.0, 2.0, 3.0, "R1", "C1"); // assertEquals(new Range(2.0, 4.0), // DatasetUtilities.iterateRangeBounds(d)); // // d = new TestIntervalCategoryDataset(); // d.addItem(0.0, 2.0, 3.0, "R1", "C1"); // assertEquals(new Range(2.0, 3.0), // DatasetUtilities.iterateRangeBounds(d)); // // // try some nulls // d = new TestIntervalCategoryDataset(); // d.addItem(null, null, null, "R1", "C1"); // assertNull(DatasetUtilities.iterateRangeBounds(d)); // // d = new TestIntervalCategoryDataset(); // d.addItem(1.0, 0.0, 0.0, "R1", "C1"); // assertEquals(new Range(1.0, 1.0), // DatasetUtilities.iterateRangeBounds(d)); // // d = new TestIntervalCategoryDataset(); // d.addItem(0.0, 1.0, 0.0, "R1", "C1"); // assertEquals(new Range(1.0, 1.0), // DatasetUtilities.iterateRangeBounds(d)); // // d = new TestIntervalCategoryDataset(); // d.addItem(0.0, 0.0, 1.0, "R1", "C1"); // assertEquals(new Range(1.0, 1.0), // DatasetUtilities.iterateRangeBounds(d)); // } /** * A test for bug 2849731. */ public void testBug2849731() {} // Defects4J: flaky method // public void testBug2849731() { // TestIntervalCategoryDataset d = new TestIntervalCategoryDataset(); // d.addItem(2.5, 2.0, 3.0, "R1", "C1"); // d.addItem(4.0, 0.0, 0.0, "R2", "C1"); // assertEquals(new Range(2.0, 4.0), // DatasetUtilities.iterateRangeBounds(d)); // } /** * Another test for bug 2849731. */ public void testBug2849731_2() { XYIntervalSeriesCollection d = new XYIntervalSeriesCollection(); XYIntervalSeries s = new XYIntervalSeries("S1"); s.add(1.0, Double.NaN, Double.NaN, Double.NaN, 1.5, Double.NaN); d.addSeries(s); Range r = DatasetUtilities.iterateDomainBounds(d); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(1.0, r.getUpperBound(), EPSILON); s.add(1.0, 1.5, Double.NaN, Double.NaN, 1.5, Double.NaN); r = DatasetUtilities.iterateDomainBounds(d); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(1.5, r.getUpperBound(), EPSILON); s.add(1.0, Double.NaN, 0.5, Double.NaN, 1.5, Double.NaN); r = DatasetUtilities.iterateDomainBounds(d); assertEquals(0.5, r.getLowerBound(), EPSILON); assertEquals(1.5, r.getUpperBound(), EPSILON); } /** * Yet another test for bug 2849731. */ public void testBug2849731_3() { XYIntervalSeriesCollection d = new XYIntervalSeriesCollection(); XYIntervalSeries s = new XYIntervalSeries("S1"); s.add(1.0, Double.NaN, Double.NaN, 1.5, Double.NaN, Double.NaN); d.addSeries(s); Range r = DatasetUtilities.iterateRangeBounds(d); assertEquals(1.5, r.getLowerBound(), EPSILON); assertEquals(1.5, r.getUpperBound(), EPSILON); s.add(1.0, 1.5, Double.NaN, Double.NaN, Double.NaN, 2.5); r = DatasetUtilities.iterateRangeBounds(d); assertEquals(1.5, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); s.add(1.0, Double.NaN, 0.5, Double.NaN, 3.5, Double.NaN); r = DatasetUtilities.iterateRangeBounds(d); assertEquals(1.5, r.getLowerBound(), EPSILON); assertEquals(3.5, r.getUpperBound(), EPSILON); } }
[ { "be_test_class_file": "org/jfree/data/general/DatasetUtilities.java", "be_test_class_name": "org.jfree.data.general.DatasetUtilities", "be_test_function_name": "iterateDomainBounds", "be_test_function_signature": "(Lorg/jfree/data/xy/XYDataset;)Lorg/jfree/data/Range;", "line_numbers": [ "726" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/general/DatasetUtilities.java", "be_test_class_name": "org.jfree.data.general.DatasetUtilities", "be_test_function_name": "iterateDomainBounds", "be_test_function_signature": "(Lorg/jfree/data/xy/XYDataset;Z)Lorg/jfree/data/Range;", "line_numbers": [ "742", "743", "745", "746", "747", "750", "751", "752", "753", "754", "755", "756", "757", "758", "759", "760", "762", "763", "764", "766", "767", "768", "772", "774", "775", "776", "777", "778", "779", "780", "781", "786", "787", "790" ], "method_line_rate": 0.7058823529411765 } ]
public class NumberAxisTests extends TestCase
public void testAutoRange4() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.setValue(100.0, "Row 1", "Column 1"); dataset.setValue(200.0, "Row 1", "Column 2"); JFreeChart chart = ChartFactory.createBarChart("Test", "Categories", "Value", dataset, false); CategoryPlot plot = (CategoryPlot) chart.getPlot(); NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoRangeIncludesZero(false); BarRenderer br = (BarRenderer) plot.getRenderer(); br.setIncludeBaseInRange(false); assertEquals(95.0, axis.getLowerBound(), EPSILON); assertEquals(205.0, axis.getUpperBound(), EPSILON); br.setIncludeBaseInRange(true); assertEquals(0.0, axis.getLowerBound(), EPSILON); assertEquals(210.0, axis.getUpperBound(), EPSILON); axis.setAutoRangeIncludesZero(true); assertEquals(0.0, axis.getLowerBound(), EPSILON); assertEquals(210.0, axis.getUpperBound(), EPSILON); br.setIncludeBaseInRange(true); assertEquals(0.0, axis.getLowerBound(), EPSILON); assertEquals(210.0, axis.getUpperBound(), EPSILON); // now replacing the dataset should update the axis range... DefaultCategoryDataset dataset2 = new DefaultCategoryDataset(); dataset2.setValue(900.0, "Row 1", "Column 1"); dataset2.setValue(1000.0, "Row 1", "Column 2"); plot.setDataset(dataset2); assertEquals(0.0, axis.getLowerBound(), EPSILON); assertEquals(1050.0, axis.getUpperBound(), EPSILON); br.setIncludeBaseInRange(false); assertEquals(0.0, axis.getLowerBound(), EPSILON); assertEquals(1050.0, axis.getUpperBound(), EPSILON); axis.setAutoRangeIncludesZero(false); assertEquals(895.0, axis.getLowerBound(), EPSILON); assertEquals(1005.0, axis.getUpperBound(), EPSILON); }
// 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.RangeType; // // // // public class NumberAxis extends ValueAxis implements Cloneable, Serializable { // private static final long serialVersionUID = 2805933088476185789L; // public static final boolean DEFAULT_AUTO_RANGE_INCLUDES_ZERO = true; // public static final boolean DEFAULT_AUTO_RANGE_STICKY_ZERO = true; // public static final NumberTickUnit DEFAULT_TICK_UNIT = new NumberTickUnit( // 1.0, new DecimalFormat("0")); // public static final boolean DEFAULT_VERTICAL_TICK_LABELS = false; // private RangeType rangeType; // private boolean autoRangeIncludesZero; // private boolean autoRangeStickyZero; // private NumberTickUnit tickUnit; // private NumberFormat numberFormatOverride; // private MarkerAxisBand markerBand; // // public NumberAxis(); // public NumberAxis(String label); // public RangeType getRangeType(); // public void setRangeType(RangeType rangeType); // public boolean getAutoRangeIncludesZero(); // public void setAutoRangeIncludesZero(boolean flag); // public boolean getAutoRangeStickyZero(); // public void setAutoRangeStickyZero(boolean flag); // public NumberTickUnit getTickUnit(); // public void setTickUnit(NumberTickUnit unit); // public void setTickUnit(NumberTickUnit unit, boolean notify, // boolean turnOffAutoSelect); // public NumberFormat getNumberFormatOverride(); // public void setNumberFormatOverride(NumberFormat formatter); // public MarkerAxisBand getMarkerBand(); // public void setMarkerBand(MarkerAxisBand band); // public void configure(); // protected void autoAdjustRange(); // public double valueToJava2D(double value, Rectangle2D area, // RectangleEdge edge); // public double java2DToValue(double java2DValue, Rectangle2D area, // RectangleEdge edge); // protected double calculateLowestVisibleTickValue(); // protected double calculateHighestVisibleTickValue(); // protected int calculateVisibleTickCount(); // public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, // Rectangle2D dataArea, RectangleEdge edge, // PlotRenderingInfo plotState); // public static TickUnitSource createStandardTickUnits(); // public static TickUnitSource createIntegerTickUnits(); // public static TickUnitSource createStandardTickUnits(Locale locale); // public static TickUnitSource createIntegerTickUnits(Locale locale); // protected double estimateMaximumTickLabelHeight(Graphics2D g2); // protected double estimateMaximumTickLabelWidth(Graphics2D g2, // TickUnit unit); // 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); // public List refreshTicks(Graphics2D g2, // AxisState state, // Rectangle2D dataArea, // RectangleEdge edge); // protected List refreshTicksHorizontal(Graphics2D g2, // Rectangle2D dataArea, RectangleEdge edge); // protected List refreshTicksVertical(Graphics2D g2, // Rectangle2D dataArea, RectangleEdge edge); // public Object clone() throws CloneNotSupportedException; // public boolean equals(Object obj); // public int hashCode(); // } // // // Abstract Java Test Class // package org.jfree.chart.axis.junit; // // import java.awt.geom.Rectangle2D; // 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.ChartFactory; // import org.jfree.chart.JFreeChart; // import org.jfree.chart.axis.NumberAxis; // import org.jfree.chart.axis.NumberTickUnit; // import org.jfree.chart.plot.CategoryPlot; // import org.jfree.chart.plot.PlotOrientation; // import org.jfree.chart.plot.XYPlot; // import org.jfree.chart.renderer.category.BarRenderer; // import org.jfree.chart.util.RectangleEdge; // import org.jfree.data.RangeType; // import org.jfree.data.category.DefaultCategoryDataset; // import org.jfree.data.xy.XYSeries; // import org.jfree.data.xy.XYSeriesCollection; // // // // public class NumberAxisTests extends TestCase { // private static final double EPSILON = 0.0000001; // // public static Test suite(); // public NumberAxisTests(String name); // public void testCloning(); // public void testEquals(); // public void testHashCode(); // public void testTranslateJava2DToValue(); // public void testSerialization(); // public void testAutoRange1(); // public void testAutoRange2(); // public void testAutoRange3(); // public void testAutoRange4(); // public void testXYAutoRange1(); // public void testXYAutoRange2(); // public void testSetLowerBound(); // } // You are a professional Java test case writer, please create a test case named `testAutoRange4` for the `NumberAxis` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * A check for the interaction between the 'autoRangeIncludesZero' flag * and the base setting in the BarRenderer. */
tests/org/jfree/chart/axis/junit/NumberAxisTests.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.DecimalFormat; import java.text.NumberFormat; import java.util.List; import java.util.Locale; 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.RangeType;
public NumberAxis(); public NumberAxis(String label); public RangeType getRangeType(); public void setRangeType(RangeType rangeType); public boolean getAutoRangeIncludesZero(); public void setAutoRangeIncludesZero(boolean flag); public boolean getAutoRangeStickyZero(); public void setAutoRangeStickyZero(boolean flag); public NumberTickUnit getTickUnit(); public void setTickUnit(NumberTickUnit unit); public void setTickUnit(NumberTickUnit unit, boolean notify, boolean turnOffAutoSelect); public NumberFormat getNumberFormatOverride(); public void setNumberFormatOverride(NumberFormat formatter); public MarkerAxisBand getMarkerBand(); public void setMarkerBand(MarkerAxisBand band); public void configure(); protected void autoAdjustRange(); public double valueToJava2D(double value, Rectangle2D area, RectangleEdge edge); public double java2DToValue(double java2DValue, Rectangle2D area, RectangleEdge edge); protected double calculateLowestVisibleTickValue(); protected double calculateHighestVisibleTickValue(); protected int calculateVisibleTickCount(); public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState); public static TickUnitSource createStandardTickUnits(); public static TickUnitSource createIntegerTickUnits(); public static TickUnitSource createStandardTickUnits(Locale locale); public static TickUnitSource createIntegerTickUnits(Locale locale); protected double estimateMaximumTickLabelHeight(Graphics2D g2); protected double estimateMaximumTickLabelWidth(Graphics2D g2, TickUnit unit); 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); public List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); protected List refreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected List refreshTicksVertical(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); public Object clone() throws CloneNotSupportedException; public boolean equals(Object obj); public int hashCode();
329
testAutoRange4
```java 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.RangeType; public class NumberAxis extends ValueAxis implements Cloneable, Serializable { private static final long serialVersionUID = 2805933088476185789L; public static final boolean DEFAULT_AUTO_RANGE_INCLUDES_ZERO = true; public static final boolean DEFAULT_AUTO_RANGE_STICKY_ZERO = true; public static final NumberTickUnit DEFAULT_TICK_UNIT = new NumberTickUnit( 1.0, new DecimalFormat("0")); public static final boolean DEFAULT_VERTICAL_TICK_LABELS = false; private RangeType rangeType; private boolean autoRangeIncludesZero; private boolean autoRangeStickyZero; private NumberTickUnit tickUnit; private NumberFormat numberFormatOverride; private MarkerAxisBand markerBand; public NumberAxis(); public NumberAxis(String label); public RangeType getRangeType(); public void setRangeType(RangeType rangeType); public boolean getAutoRangeIncludesZero(); public void setAutoRangeIncludesZero(boolean flag); public boolean getAutoRangeStickyZero(); public void setAutoRangeStickyZero(boolean flag); public NumberTickUnit getTickUnit(); public void setTickUnit(NumberTickUnit unit); public void setTickUnit(NumberTickUnit unit, boolean notify, boolean turnOffAutoSelect); public NumberFormat getNumberFormatOverride(); public void setNumberFormatOverride(NumberFormat formatter); public MarkerAxisBand getMarkerBand(); public void setMarkerBand(MarkerAxisBand band); public void configure(); protected void autoAdjustRange(); public double valueToJava2D(double value, Rectangle2D area, RectangleEdge edge); public double java2DToValue(double java2DValue, Rectangle2D area, RectangleEdge edge); protected double calculateLowestVisibleTickValue(); protected double calculateHighestVisibleTickValue(); protected int calculateVisibleTickCount(); public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState); public static TickUnitSource createStandardTickUnits(); public static TickUnitSource createIntegerTickUnits(); public static TickUnitSource createStandardTickUnits(Locale locale); public static TickUnitSource createIntegerTickUnits(Locale locale); protected double estimateMaximumTickLabelHeight(Graphics2D g2); protected double estimateMaximumTickLabelWidth(Graphics2D g2, TickUnit unit); 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); public List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); protected List refreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected List refreshTicksVertical(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); public Object clone() throws CloneNotSupportedException; public boolean equals(Object obj); public int hashCode(); } // Abstract Java Test Class package org.jfree.chart.axis.junit; import java.awt.geom.Rectangle2D; 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.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.NumberTickUnit; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.chart.util.RectangleEdge; import org.jfree.data.RangeType; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; public class NumberAxisTests extends TestCase { private static final double EPSILON = 0.0000001; public static Test suite(); public NumberAxisTests(String name); public void testCloning(); public void testEquals(); public void testHashCode(); public void testTranslateJava2DToValue(); public void testSerialization(); public void testAutoRange1(); public void testAutoRange2(); public void testAutoRange3(); public void testAutoRange4(); public void testXYAutoRange1(); public void testXYAutoRange2(); public void testSetLowerBound(); } ``` You are a professional Java test case writer, please create a test case named `testAutoRange4` for the `NumberAxis` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * A check for the interaction between the 'autoRangeIncludesZero' flag * and the base setting in the BarRenderer. */
288
// 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.RangeType; // // // // public class NumberAxis extends ValueAxis implements Cloneable, Serializable { // private static final long serialVersionUID = 2805933088476185789L; // public static final boolean DEFAULT_AUTO_RANGE_INCLUDES_ZERO = true; // public static final boolean DEFAULT_AUTO_RANGE_STICKY_ZERO = true; // public static final NumberTickUnit DEFAULT_TICK_UNIT = new NumberTickUnit( // 1.0, new DecimalFormat("0")); // public static final boolean DEFAULT_VERTICAL_TICK_LABELS = false; // private RangeType rangeType; // private boolean autoRangeIncludesZero; // private boolean autoRangeStickyZero; // private NumberTickUnit tickUnit; // private NumberFormat numberFormatOverride; // private MarkerAxisBand markerBand; // // public NumberAxis(); // public NumberAxis(String label); // public RangeType getRangeType(); // public void setRangeType(RangeType rangeType); // public boolean getAutoRangeIncludesZero(); // public void setAutoRangeIncludesZero(boolean flag); // public boolean getAutoRangeStickyZero(); // public void setAutoRangeStickyZero(boolean flag); // public NumberTickUnit getTickUnit(); // public void setTickUnit(NumberTickUnit unit); // public void setTickUnit(NumberTickUnit unit, boolean notify, // boolean turnOffAutoSelect); // public NumberFormat getNumberFormatOverride(); // public void setNumberFormatOverride(NumberFormat formatter); // public MarkerAxisBand getMarkerBand(); // public void setMarkerBand(MarkerAxisBand band); // public void configure(); // protected void autoAdjustRange(); // public double valueToJava2D(double value, Rectangle2D area, // RectangleEdge edge); // public double java2DToValue(double java2DValue, Rectangle2D area, // RectangleEdge edge); // protected double calculateLowestVisibleTickValue(); // protected double calculateHighestVisibleTickValue(); // protected int calculateVisibleTickCount(); // public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, // Rectangle2D dataArea, RectangleEdge edge, // PlotRenderingInfo plotState); // public static TickUnitSource createStandardTickUnits(); // public static TickUnitSource createIntegerTickUnits(); // public static TickUnitSource createStandardTickUnits(Locale locale); // public static TickUnitSource createIntegerTickUnits(Locale locale); // protected double estimateMaximumTickLabelHeight(Graphics2D g2); // protected double estimateMaximumTickLabelWidth(Graphics2D g2, // TickUnit unit); // 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); // public List refreshTicks(Graphics2D g2, // AxisState state, // Rectangle2D dataArea, // RectangleEdge edge); // protected List refreshTicksHorizontal(Graphics2D g2, // Rectangle2D dataArea, RectangleEdge edge); // protected List refreshTicksVertical(Graphics2D g2, // Rectangle2D dataArea, RectangleEdge edge); // public Object clone() throws CloneNotSupportedException; // public boolean equals(Object obj); // public int hashCode(); // } // // // Abstract Java Test Class // package org.jfree.chart.axis.junit; // // import java.awt.geom.Rectangle2D; // 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.ChartFactory; // import org.jfree.chart.JFreeChart; // import org.jfree.chart.axis.NumberAxis; // import org.jfree.chart.axis.NumberTickUnit; // import org.jfree.chart.plot.CategoryPlot; // import org.jfree.chart.plot.PlotOrientation; // import org.jfree.chart.plot.XYPlot; // import org.jfree.chart.renderer.category.BarRenderer; // import org.jfree.chart.util.RectangleEdge; // import org.jfree.data.RangeType; // import org.jfree.data.category.DefaultCategoryDataset; // import org.jfree.data.xy.XYSeries; // import org.jfree.data.xy.XYSeriesCollection; // // // // public class NumberAxisTests extends TestCase { // private static final double EPSILON = 0.0000001; // // public static Test suite(); // public NumberAxisTests(String name); // public void testCloning(); // public void testEquals(); // public void testHashCode(); // public void testTranslateJava2DToValue(); // public void testSerialization(); // public void testAutoRange1(); // public void testAutoRange2(); // public void testAutoRange3(); // public void testAutoRange4(); // public void testXYAutoRange1(); // public void testXYAutoRange2(); // public void testSetLowerBound(); // } // You are a professional Java test case writer, please create a test case named `testAutoRange4` for the `NumberAxis` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * A check for the interaction between the 'autoRangeIncludesZero' flag * and the base setting in the BarRenderer. */ public void testAutoRange4() {
/** * A check for the interaction between the 'autoRangeIncludesZero' flag * and the base setting in the BarRenderer. */
1
org.jfree.chart.axis.NumberAxis
tests
```java 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.RangeType; public class NumberAxis extends ValueAxis implements Cloneable, Serializable { private static final long serialVersionUID = 2805933088476185789L; public static final boolean DEFAULT_AUTO_RANGE_INCLUDES_ZERO = true; public static final boolean DEFAULT_AUTO_RANGE_STICKY_ZERO = true; public static final NumberTickUnit DEFAULT_TICK_UNIT = new NumberTickUnit( 1.0, new DecimalFormat("0")); public static final boolean DEFAULT_VERTICAL_TICK_LABELS = false; private RangeType rangeType; private boolean autoRangeIncludesZero; private boolean autoRangeStickyZero; private NumberTickUnit tickUnit; private NumberFormat numberFormatOverride; private MarkerAxisBand markerBand; public NumberAxis(); public NumberAxis(String label); public RangeType getRangeType(); public void setRangeType(RangeType rangeType); public boolean getAutoRangeIncludesZero(); public void setAutoRangeIncludesZero(boolean flag); public boolean getAutoRangeStickyZero(); public void setAutoRangeStickyZero(boolean flag); public NumberTickUnit getTickUnit(); public void setTickUnit(NumberTickUnit unit); public void setTickUnit(NumberTickUnit unit, boolean notify, boolean turnOffAutoSelect); public NumberFormat getNumberFormatOverride(); public void setNumberFormatOverride(NumberFormat formatter); public MarkerAxisBand getMarkerBand(); public void setMarkerBand(MarkerAxisBand band); public void configure(); protected void autoAdjustRange(); public double valueToJava2D(double value, Rectangle2D area, RectangleEdge edge); public double java2DToValue(double java2DValue, Rectangle2D area, RectangleEdge edge); protected double calculateLowestVisibleTickValue(); protected double calculateHighestVisibleTickValue(); protected int calculateVisibleTickCount(); public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState); public static TickUnitSource createStandardTickUnits(); public static TickUnitSource createIntegerTickUnits(); public static TickUnitSource createStandardTickUnits(Locale locale); public static TickUnitSource createIntegerTickUnits(Locale locale); protected double estimateMaximumTickLabelHeight(Graphics2D g2); protected double estimateMaximumTickLabelWidth(Graphics2D g2, TickUnit unit); 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); public List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge); protected List refreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); protected List refreshTicksVertical(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge); public Object clone() throws CloneNotSupportedException; public boolean equals(Object obj); public int hashCode(); } // Abstract Java Test Class package org.jfree.chart.axis.junit; import java.awt.geom.Rectangle2D; 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.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.NumberTickUnit; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.chart.util.RectangleEdge; import org.jfree.data.RangeType; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; public class NumberAxisTests extends TestCase { private static final double EPSILON = 0.0000001; public static Test suite(); public NumberAxisTests(String name); public void testCloning(); public void testEquals(); public void testHashCode(); public void testTranslateJava2DToValue(); public void testSerialization(); public void testAutoRange1(); public void testAutoRange2(); public void testAutoRange3(); public void testAutoRange4(); public void testXYAutoRange1(); public void testXYAutoRange2(); public void testSetLowerBound(); } ``` You are a professional Java test case writer, please create a test case named `testAutoRange4` for the `NumberAxis` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * A check for the interaction between the 'autoRangeIncludesZero' flag * and the base setting in the BarRenderer. */ public void testAutoRange4() { ```
public class NumberAxis extends ValueAxis implements Cloneable, Serializable
package org.jfree.chart.axis.junit; import java.awt.geom.Rectangle2D; 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.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.NumberTickUnit; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.chart.util.RectangleEdge; import org.jfree.data.RangeType; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection;
public static Test suite(); public NumberAxisTests(String name); public void testCloning(); public void testEquals(); public void testHashCode(); public void testTranslateJava2DToValue(); public void testSerialization(); public void testAutoRange1(); public void testAutoRange2(); public void testAutoRange3(); public void testAutoRange4(); public void testXYAutoRange1(); public void testXYAutoRange2(); public void testSetLowerBound();
8be2289383de597004f2938a167f7fa5b2d2affee68d46b1789322caf5cd63f0
[ "org.jfree.chart.axis.junit.NumberAxisTests::testAutoRange4" ]
private static final long serialVersionUID = 2805933088476185789L; public static final boolean DEFAULT_AUTO_RANGE_INCLUDES_ZERO = true; public static final boolean DEFAULT_AUTO_RANGE_STICKY_ZERO = true; public static final NumberTickUnit DEFAULT_TICK_UNIT = new NumberTickUnit( 1.0, new DecimalFormat("0")); public static final boolean DEFAULT_VERTICAL_TICK_LABELS = false; private RangeType rangeType; private boolean autoRangeIncludesZero; private boolean autoRangeStickyZero; private NumberTickUnit tickUnit; private NumberFormat numberFormatOverride; private MarkerAxisBand markerBand;
public void testAutoRange4()
private static final double EPSILON = 0.0000001;
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.] * * -------------------- * NumberAxisTests.java * -------------------- * (C) Copyright 2003-2008, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 26-Mar-2003 : Version 1 (DG); * 14-Aug-2003 : Added tests for equals() method (DG); * 05-Oct-2004 : Added tests to pick up a bug in the auto-range calculation for * a domain axis on an XYPlot using an XYSeriesCollection (DG); * 07-Jan-2005 : Added test for hashCode() (DG); * 11-Jan-2006 : Fixed testAutoRange2() and testAutoRange3() following changes * to BarRenderer (DG); * 20-Feb-2006 : Added rangeType field to equals() test (DG); * 20-Jun-2007 : Removed JCommon dependencies (DG); * */ package org.jfree.chart.axis.junit; import java.awt.geom.Rectangle2D; 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.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.NumberTickUnit; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.chart.util.RectangleEdge; import org.jfree.data.RangeType; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; /** * Tests for the {@link NumberAxis} class. */ public class NumberAxisTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(NumberAxisTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public NumberAxisTests(String name) { super(name); } /** * Confirm that cloning works. */ public void testCloning() { NumberAxis a1 = new NumberAxis("Test"); NumberAxis a2 = null; try { a2 = (NumberAxis) a1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(a1 != a2); assertTrue(a1.getClass() == a2.getClass()); assertTrue(a1.equals(a2)); } /** * Confirm that the equals method can distinguish all the required fields. */ public void testEquals() { NumberAxis a1 = new NumberAxis("Test"); NumberAxis a2 = new NumberAxis("Test"); assertTrue(a1.equals(a2)); //private boolean autoRangeIncludesZero; a1.setAutoRangeIncludesZero(false); assertFalse(a1.equals(a2)); a2.setAutoRangeIncludesZero(false); assertTrue(a1.equals(a2)); //private boolean autoRangeStickyZero; a1.setAutoRangeStickyZero(false); assertFalse(a1.equals(a2)); a2.setAutoRangeStickyZero(false); assertTrue(a1.equals(a2)); //private NumberTickUnit tickUnit; a1.setTickUnit(new NumberTickUnit(25.0)); assertFalse(a1.equals(a2)); a2.setTickUnit(new NumberTickUnit(25.0)); assertTrue(a1.equals(a2)); //private NumberFormat numberFormatOverride; a1.setNumberFormatOverride(new DecimalFormat("0.00")); assertFalse(a1.equals(a2)); a2.setNumberFormatOverride(new DecimalFormat("0.00")); assertTrue(a1.equals(a2)); a1.setRangeType(RangeType.POSITIVE); assertFalse(a1.equals(a2)); a2.setRangeType(RangeType.POSITIVE); assertTrue(a1.equals(a2)); } /** * Two objects that are equal are required to return the same hashCode. */ public void testHashCode() { NumberAxis a1 = new NumberAxis("Test"); NumberAxis a2 = new NumberAxis("Test"); assertTrue(a1.equals(a2)); int h1 = a1.hashCode(); int h2 = a2.hashCode(); assertEquals(h1, h2); } private static final double EPSILON = 0.0000001; /** * Test the translation of Java2D values to data values. */ public void testTranslateJava2DToValue() { NumberAxis axis = new NumberAxis(); 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); assertEquals(y1, 95.8333333, EPSILON); double y2 = axis.java2DToValue(75.0, dataArea, RectangleEdge.RIGHT); assertEquals(y2, 95.8333333, EPSILON); double x1 = axis.java2DToValue(75.0, dataArea, RectangleEdge.TOP); assertEquals(x1, 58.125, EPSILON); double x2 = axis.java2DToValue(75.0, dataArea, RectangleEdge.BOTTOM); assertEquals(x2, 58.125, EPSILON); axis.setInverted(true); double y3 = axis.java2DToValue(75.0, dataArea, RectangleEdge.LEFT); assertEquals(y3, 54.1666667, EPSILON); double y4 = axis.java2DToValue(75.0, dataArea, RectangleEdge.RIGHT); assertEquals(y4, 54.1666667, EPSILON); double x3 = axis.java2DToValue(75.0, dataArea, RectangleEdge.TOP); assertEquals(x3, 91.875, EPSILON); double x4 = axis.java2DToValue(75.0, dataArea, RectangleEdge.BOTTOM); assertEquals(x4, 91.875, EPSILON); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { NumberAxis a1 = new NumberAxis("Test Axis"); NumberAxis 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 = (NumberAxis) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(a1, a2); } /** * A simple test for the auto-range calculation looking at a * NumberAxis used as the range axis for a CategoryPlot. */ public void testAutoRange1() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.setValue(100.0, "Row 1", "Column 1"); dataset.setValue(200.0, "Row 1", "Column 2"); JFreeChart chart = ChartFactory.createBarChart("Test", "Categories", "Value", dataset, false); CategoryPlot plot = (CategoryPlot) chart.getPlot(); NumberAxis axis = (NumberAxis) plot.getRangeAxis(); assertEquals(axis.getLowerBound(), 0.0, EPSILON); assertEquals(axis.getUpperBound(), 210.0, EPSILON); } /** * A simple test for the auto-range calculation looking at a * NumberAxis used as the range axis for a CategoryPlot. In this * case, the 'autoRangeIncludesZero' flag is set to false. */ public void testAutoRange2() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.setValue(100.0, "Row 1", "Column 1"); dataset.setValue(200.0, "Row 1", "Column 2"); JFreeChart chart = ChartFactory.createLineChart("Test", "Categories", "Value", dataset, false); CategoryPlot plot = (CategoryPlot) chart.getPlot(); NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoRangeIncludesZero(false); assertEquals(axis.getLowerBound(), 95.0, EPSILON); assertEquals(axis.getUpperBound(), 205.0, EPSILON); } /** * A simple test for the auto-range calculation looking at a * NumberAxis used as the range axis for a CategoryPlot. In this * case, the 'autoRangeIncludesZero' flag is set to false AND the * original dataset is replaced with a new dataset. */ public void testAutoRange3() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.setValue(100.0, "Row 1", "Column 1"); dataset.setValue(200.0, "Row 1", "Column 2"); JFreeChart chart = ChartFactory.createLineChart("Test", "Categories", "Value", dataset, false); CategoryPlot plot = (CategoryPlot) chart.getPlot(); NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoRangeIncludesZero(false); assertEquals(axis.getLowerBound(), 95.0, EPSILON); assertEquals(axis.getUpperBound(), 205.0, EPSILON); // now replacing the dataset should update the axis range... DefaultCategoryDataset dataset2 = new DefaultCategoryDataset(); dataset2.setValue(900.0, "Row 1", "Column 1"); dataset2.setValue(1000.0, "Row 1", "Column 2"); plot.setDataset(dataset2); assertEquals(axis.getLowerBound(), 895.0, EPSILON); assertEquals(axis.getUpperBound(), 1005.0, EPSILON); } /** * A check for the interaction between the 'autoRangeIncludesZero' flag * and the base setting in the BarRenderer. */ public void testAutoRange4() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.setValue(100.0, "Row 1", "Column 1"); dataset.setValue(200.0, "Row 1", "Column 2"); JFreeChart chart = ChartFactory.createBarChart("Test", "Categories", "Value", dataset, false); CategoryPlot plot = (CategoryPlot) chart.getPlot(); NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoRangeIncludesZero(false); BarRenderer br = (BarRenderer) plot.getRenderer(); br.setIncludeBaseInRange(false); assertEquals(95.0, axis.getLowerBound(), EPSILON); assertEquals(205.0, axis.getUpperBound(), EPSILON); br.setIncludeBaseInRange(true); assertEquals(0.0, axis.getLowerBound(), EPSILON); assertEquals(210.0, axis.getUpperBound(), EPSILON); axis.setAutoRangeIncludesZero(true); assertEquals(0.0, axis.getLowerBound(), EPSILON); assertEquals(210.0, axis.getUpperBound(), EPSILON); br.setIncludeBaseInRange(true); assertEquals(0.0, axis.getLowerBound(), EPSILON); assertEquals(210.0, axis.getUpperBound(), EPSILON); // now replacing the dataset should update the axis range... DefaultCategoryDataset dataset2 = new DefaultCategoryDataset(); dataset2.setValue(900.0, "Row 1", "Column 1"); dataset2.setValue(1000.0, "Row 1", "Column 2"); plot.setDataset(dataset2); assertEquals(0.0, axis.getLowerBound(), EPSILON); assertEquals(1050.0, axis.getUpperBound(), EPSILON); br.setIncludeBaseInRange(false); assertEquals(0.0, axis.getLowerBound(), EPSILON); assertEquals(1050.0, axis.getUpperBound(), EPSILON); axis.setAutoRangeIncludesZero(false); assertEquals(895.0, axis.getLowerBound(), EPSILON); assertEquals(1005.0, axis.getUpperBound(), EPSILON); } /** * Checks that the auto-range for the domain axis on an XYPlot is * working as expected. */ public void testXYAutoRange1() { XYSeries series = new XYSeries("Series 1"); series.add(1.0, 1.0); series.add(2.0, 2.0); series.add(3.0, 3.0); XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(series); JFreeChart chart = ChartFactory.createScatterPlot("Test", "X", "Y", dataset, false); XYPlot plot = (XYPlot) chart.getPlot(); NumberAxis axis = (NumberAxis) plot.getDomainAxis(); axis.setAutoRangeIncludesZero(false); assertEquals(0.9, axis.getLowerBound(), EPSILON); assertEquals(3.1, axis.getUpperBound(), EPSILON); } /** * Checks that the auto-range for the range axis on an XYPlot is * working as expected. */ public void testXYAutoRange2() { XYSeries series = new XYSeries("Series 1"); series.add(1.0, 1.0); series.add(2.0, 2.0); series.add(3.0, 3.0); XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(series); JFreeChart chart = ChartFactory.createScatterPlot("Test", "X", "Y", dataset, false); XYPlot plot = (XYPlot) chart.getPlot(); NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setAutoRangeIncludesZero(false); assertEquals(0.9, axis.getLowerBound(), EPSILON); assertEquals(3.1, axis.getUpperBound(), EPSILON); } // /** // * Some checks for the setRangeType() method. // */ // public void testSetRangeType() { // // NumberAxis axis = new NumberAxis("X"); // axis.setRangeType(RangeType.POSITIVE); // assertEquals(RangeType.POSITIVE, axis.getRangeType()); // // // test a change to RangeType.POSITIVE // axis.setRangeType(RangeType.FULL); // axis.setRange(-5.0, 5.0); // axis.setRangeType(RangeType.POSITIVE); // assertEquals(new Range(0.0, 5.0), axis.getRange()); // // axis.setRangeType(RangeType.FULL); // axis.setRange(-10.0, -5.0); // axis.setRangeType(RangeType.POSITIVE); // assertEquals(new Range(0.0, axis.getAutoRangeMinimumSize()), // axis.getRange()); // // // test a change to RangeType.NEGATIVE // axis.setRangeType(RangeType.FULL); // axis.setRange(-5.0, 5.0); // axis.setRangeType(RangeType.NEGATIVE); // assertEquals(new Range(-5.0, 0.0), axis.getRange()); // // axis.setRangeType(RangeType.FULL); // axis.setRange(5.0, 10.0); // axis.setRangeType(RangeType.NEGATIVE); // assertEquals(new Range(-axis.getAutoRangeMinimumSize(), 0.0), // axis.getRange()); // // // try null // boolean pass = false; // try { // axis.setRangeType(null); // } // catch (IllegalArgumentException e) { // pass = true; // } // assertTrue(pass); // } /** * Some checks for the setLowerBound() method. */ public void testSetLowerBound() { NumberAxis axis = new NumberAxis("X"); axis.setRange(0.0, 10.0); axis.setLowerBound(5.0); assertEquals(5.0, axis.getLowerBound(), EPSILON); axis.setLowerBound(10.0); assertEquals(10.0, axis.getLowerBound(), EPSILON); assertEquals(11.0, axis.getUpperBound(), EPSILON); //axis.setRangeType(RangeType.POSITIVE); //axis.setLowerBound(-5.0); //assertEquals(0.0, axis.getLowerBound(), EPSILON); } }
[ { "be_test_class_file": "org/jfree/chart/axis/NumberAxis.java", "be_test_class_name": "org.jfree.chart.axis.NumberAxis", "be_test_function_name": "autoAdjustRange", "be_test_function_signature": "()V", "line_numbers": [ "426", "427", "428", "431", "432", "434", "435", "436", "439", "440", "441", "442", "443", "445", "446", "447", "450", "451", "452", "454", "457", "458", "459", "463", "464", "465", "466", "467", "468", "469", "470", "471", "473", "474", "475", "476", "479", "480", "481", "482", "487", "488", "489", "492", "494", "495", "498", "502", "503", "507", "510" ], "method_line_rate": 0.5098039215686274 }, { "be_test_class_file": "org/jfree/chart/axis/NumberAxis.java", "be_test_class_name": "org.jfree.chart.axis.NumberAxis", "be_test_function_name": "configure", "be_test_function_signature": "()V", "line_numbers": [ "416", "417", "419" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/NumberAxis.java", "be_test_class_name": "org.jfree.chart.axis.NumberAxis", "be_test_function_name": "createStandardTickUnits", "be_test_function_signature": "()Lorg/jfree/chart/axis/TickUnitSource;", "line_numbers": [ "703", "704", "705", "706", "707", "708", "709", "710", "711", "712", "713", "714", "715", "716", "720", "721", "722", "723", "724", "725", "726", "727", "728", "729", "730", "731", "732", "733", "734", "735", "736", "737", "738", "739", "740", "742", "743", "744", "745", "746", "747", "748", "749", "750", "751", "752", "753", "754", "755", "756", "757", "758", "759", "760", "761", "762", "764", "765", "766", "767", "768", "769", "770", "771", "772", "773", "774", "775", "776", "777", "778", "779", "780", "781", "782", "783", "784", "786" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/NumberAxis.java", "be_test_class_name": "org.jfree.chart.axis.NumberAxis", "be_test_function_name": "getAutoRangeIncludesZero", "be_test_function_signature": "()Z", "line_numbers": [ "243" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/NumberAxis.java", "be_test_class_name": "org.jfree.chart.axis.NumberAxis", "be_test_function_name": "getAutoRangeStickyZero", "be_test_function_signature": "()Z", "line_numbers": [ "278" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/chart/axis/NumberAxis.java", "be_test_class_name": "org.jfree.chart.axis.NumberAxis", "be_test_function_name": "setAutoRangeIncludesZero", "be_test_function_signature": "(Z)V", "line_numbers": [ "260", "261", "262", "263", "265", "267" ], "method_line_rate": 1 } ]
public class HypergeometricDistributionTest extends IntegerDistributionAbstractTest
@Test public void testDegenerateNoFailures() { HypergeometricDistribution dist = new HypergeometricDistribution(5,5,3); setDistribution(dist); setCumulativeTestPoints(new int[] {-1, 0, 1, 3, 10 }); setCumulativeTestValues(new double[] {0d, 0d, 0d, 1d, 1d}); setDensityTestPoints(new int[] {-1, 0, 1, 3, 10}); setDensityTestValues(new double[] {0d, 0d, 0d, 1d, 0d}); setInverseCumulativeTestPoints(new double[] {0.1d, 0.5d}); setInverseCumulativeTestValues(new int[] {3, 3}); verifyDensities(); verifyCumulativeProbabilities(); verifyInverseCumulativeProbabilities(); Assert.assertEquals(dist.getSupportLowerBound(), 3); Assert.assertEquals(dist.getSupportUpperBound(), 3); }
// // Abstract Java Tested Class // package org.apache.commons.math3.distribution; // // import org.apache.commons.math3.exception.NotPositiveException; // import org.apache.commons.math3.exception.NotStrictlyPositiveException; // import org.apache.commons.math3.exception.NumberIsTooLargeException; // import org.apache.commons.math3.exception.util.LocalizedFormats; // import org.apache.commons.math3.util.FastMath; // import org.apache.commons.math3.random.RandomGenerator; // import org.apache.commons.math3.random.Well19937c; // // // // public class HypergeometricDistribution extends AbstractIntegerDistribution { // private static final long serialVersionUID = -436928820673516179L; // private final int numberOfSuccesses; // private final int populationSize; // private final int sampleSize; // private double numericalVariance = Double.NaN; // private boolean numericalVarianceIsCalculated = false; // // public HypergeometricDistribution(int populationSize, int numberOfSuccesses, int sampleSize) // throws NotPositiveException, NotStrictlyPositiveException, NumberIsTooLargeException; // public HypergeometricDistribution(RandomGenerator rng, // int populationSize, // int numberOfSuccesses, // int sampleSize) // throws NotPositiveException, NotStrictlyPositiveException, NumberIsTooLargeException; // public double cumulativeProbability(int x); // private int[] getDomain(int n, int m, int k); // private int getLowerDomain(int n, int m, int k); // public int getNumberOfSuccesses(); // public int getPopulationSize(); // public int getSampleSize(); // private int getUpperDomain(int m, int k); // public double probability(int x); // public double upperCumulativeProbability(int x); // private double innerCumulativeProbability(int x0, int x1, int dx); // public double getNumericalMean(); // public double getNumericalVariance(); // protected double calculateNumericalVariance(); // public int getSupportLowerBound(); // public int getSupportUpperBound(); // public boolean isSupportConnected(); // } // // // Abstract Java Test Class // package org.apache.commons.math3.distribution; // // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.exception.NotPositiveException; // import org.apache.commons.math3.exception.NotStrictlyPositiveException; // import org.apache.commons.math3.exception.NumberIsTooLargeException; // import org.apache.commons.math3.util.Precision; // import org.junit.Assert; // import org.junit.Test; // // // // public class HypergeometricDistributionTest extends IntegerDistributionAbstractTest { // // // @Override // public IntegerDistribution makeDistribution(); // @Override // public int[] makeDensityTestPoints(); // @Override // public double[] makeDensityTestValues(); // @Override // public int[] makeCumulativeTestPoints(); // @Override // public double[] makeCumulativeTestValues(); // @Override // public double[] makeInverseCumulativeTestPoints(); // @Override // public int[] makeInverseCumulativeTestValues(); // @Test // public void testDegenerateNoFailures(); // @Test // public void testDegenerateNoSuccesses(); // @Test // public void testDegenerateFullSample(); // @Test // public void testPreconditions(); // @Test // public void testAccessors(); // @Test // public void testLargeValues(); // private void testHypergeometricDistributionProbabilities(int populationSize, int sampleSize, int numberOfSucceses, double[][] data); // @Test // public void testMoreLargeValues(); // @Test // public void testMoments(); // @Test // public void testMath644(); // @Test // public void testMath1021(); // } // You are a professional Java test case writer, please create a test case named `testDegenerateNoFailures` for the `HypergeometricDistribution` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** Verify that if there are no failures, mass is concentrated on sampleSize */
src/test/java/org/apache/commons/math3/distribution/HypergeometricDistributionTest.java
package org.apache.commons.math3.distribution; import org.apache.commons.math3.exception.NotPositiveException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.random.RandomGenerator; import org.apache.commons.math3.random.Well19937c;
public HypergeometricDistribution(int populationSize, int numberOfSuccesses, int sampleSize) throws NotPositiveException, NotStrictlyPositiveException, NumberIsTooLargeException; public HypergeometricDistribution(RandomGenerator rng, int populationSize, int numberOfSuccesses, int sampleSize) throws NotPositiveException, NotStrictlyPositiveException, NumberIsTooLargeException; public double cumulativeProbability(int x); private int[] getDomain(int n, int m, int k); private int getLowerDomain(int n, int m, int k); public int getNumberOfSuccesses(); public int getPopulationSize(); public int getSampleSize(); private int getUpperDomain(int m, int k); public double probability(int x); public double upperCumulativeProbability(int x); private double innerCumulativeProbability(int x0, int x1, int dx); public double getNumericalMean(); public double getNumericalVariance(); protected double calculateNumericalVariance(); public int getSupportLowerBound(); public int getSupportUpperBound(); public boolean isSupportConnected();
101
testDegenerateNoFailures
```java // Abstract Java Tested Class package org.apache.commons.math3.distribution; import org.apache.commons.math3.exception.NotPositiveException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.random.RandomGenerator; import org.apache.commons.math3.random.Well19937c; public class HypergeometricDistribution extends AbstractIntegerDistribution { private static final long serialVersionUID = -436928820673516179L; private final int numberOfSuccesses; private final int populationSize; private final int sampleSize; private double numericalVariance = Double.NaN; private boolean numericalVarianceIsCalculated = false; public HypergeometricDistribution(int populationSize, int numberOfSuccesses, int sampleSize) throws NotPositiveException, NotStrictlyPositiveException, NumberIsTooLargeException; public HypergeometricDistribution(RandomGenerator rng, int populationSize, int numberOfSuccesses, int sampleSize) throws NotPositiveException, NotStrictlyPositiveException, NumberIsTooLargeException; public double cumulativeProbability(int x); private int[] getDomain(int n, int m, int k); private int getLowerDomain(int n, int m, int k); public int getNumberOfSuccesses(); public int getPopulationSize(); public int getSampleSize(); private int getUpperDomain(int m, int k); public double probability(int x); public double upperCumulativeProbability(int x); private double innerCumulativeProbability(int x0, int x1, int dx); public double getNumericalMean(); public double getNumericalVariance(); protected double calculateNumericalVariance(); public int getSupportLowerBound(); public int getSupportUpperBound(); public boolean isSupportConnected(); } // Abstract Java Test Class package org.apache.commons.math3.distribution; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.exception.NotPositiveException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.util.Precision; import org.junit.Assert; import org.junit.Test; public class HypergeometricDistributionTest extends IntegerDistributionAbstractTest { @Override public IntegerDistribution makeDistribution(); @Override public int[] makeDensityTestPoints(); @Override public double[] makeDensityTestValues(); @Override public int[] makeCumulativeTestPoints(); @Override public double[] makeCumulativeTestValues(); @Override public double[] makeInverseCumulativeTestPoints(); @Override public int[] makeInverseCumulativeTestValues(); @Test public void testDegenerateNoFailures(); @Test public void testDegenerateNoSuccesses(); @Test public void testDegenerateFullSample(); @Test public void testPreconditions(); @Test public void testAccessors(); @Test public void testLargeValues(); private void testHypergeometricDistributionProbabilities(int populationSize, int sampleSize, int numberOfSucceses, double[][] data); @Test public void testMoreLargeValues(); @Test public void testMoments(); @Test public void testMath644(); @Test public void testMath1021(); } ``` You are a professional Java test case writer, please create a test case named `testDegenerateNoFailures` for the `HypergeometricDistribution` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** Verify that if there are no failures, mass is concentrated on sampleSize */
86
// // Abstract Java Tested Class // package org.apache.commons.math3.distribution; // // import org.apache.commons.math3.exception.NotPositiveException; // import org.apache.commons.math3.exception.NotStrictlyPositiveException; // import org.apache.commons.math3.exception.NumberIsTooLargeException; // import org.apache.commons.math3.exception.util.LocalizedFormats; // import org.apache.commons.math3.util.FastMath; // import org.apache.commons.math3.random.RandomGenerator; // import org.apache.commons.math3.random.Well19937c; // // // // public class HypergeometricDistribution extends AbstractIntegerDistribution { // private static final long serialVersionUID = -436928820673516179L; // private final int numberOfSuccesses; // private final int populationSize; // private final int sampleSize; // private double numericalVariance = Double.NaN; // private boolean numericalVarianceIsCalculated = false; // // public HypergeometricDistribution(int populationSize, int numberOfSuccesses, int sampleSize) // throws NotPositiveException, NotStrictlyPositiveException, NumberIsTooLargeException; // public HypergeometricDistribution(RandomGenerator rng, // int populationSize, // int numberOfSuccesses, // int sampleSize) // throws NotPositiveException, NotStrictlyPositiveException, NumberIsTooLargeException; // public double cumulativeProbability(int x); // private int[] getDomain(int n, int m, int k); // private int getLowerDomain(int n, int m, int k); // public int getNumberOfSuccesses(); // public int getPopulationSize(); // public int getSampleSize(); // private int getUpperDomain(int m, int k); // public double probability(int x); // public double upperCumulativeProbability(int x); // private double innerCumulativeProbability(int x0, int x1, int dx); // public double getNumericalMean(); // public double getNumericalVariance(); // protected double calculateNumericalVariance(); // public int getSupportLowerBound(); // public int getSupportUpperBound(); // public boolean isSupportConnected(); // } // // // Abstract Java Test Class // package org.apache.commons.math3.distribution; // // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.exception.NotPositiveException; // import org.apache.commons.math3.exception.NotStrictlyPositiveException; // import org.apache.commons.math3.exception.NumberIsTooLargeException; // import org.apache.commons.math3.util.Precision; // import org.junit.Assert; // import org.junit.Test; // // // // public class HypergeometricDistributionTest extends IntegerDistributionAbstractTest { // // // @Override // public IntegerDistribution makeDistribution(); // @Override // public int[] makeDensityTestPoints(); // @Override // public double[] makeDensityTestValues(); // @Override // public int[] makeCumulativeTestPoints(); // @Override // public double[] makeCumulativeTestValues(); // @Override // public double[] makeInverseCumulativeTestPoints(); // @Override // public int[] makeInverseCumulativeTestValues(); // @Test // public void testDegenerateNoFailures(); // @Test // public void testDegenerateNoSuccesses(); // @Test // public void testDegenerateFullSample(); // @Test // public void testPreconditions(); // @Test // public void testAccessors(); // @Test // public void testLargeValues(); // private void testHypergeometricDistributionProbabilities(int populationSize, int sampleSize, int numberOfSucceses, double[][] data); // @Test // public void testMoreLargeValues(); // @Test // public void testMoments(); // @Test // public void testMath644(); // @Test // public void testMath1021(); // } // You are a professional Java test case writer, please create a test case named `testDegenerateNoFailures` for the `HypergeometricDistribution` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** Verify that if there are no failures, mass is concentrated on sampleSize */ //-------------------- Additional test cases ------------------------------ @Test public void testDegenerateNoFailures() {
/** Verify that if there are no failures, mass is concentrated on sampleSize */ //-------------------- Additional test cases ------------------------------
1
org.apache.commons.math3.distribution.HypergeometricDistribution
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.math3.distribution; import org.apache.commons.math3.exception.NotPositiveException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.random.RandomGenerator; import org.apache.commons.math3.random.Well19937c; public class HypergeometricDistribution extends AbstractIntegerDistribution { private static final long serialVersionUID = -436928820673516179L; private final int numberOfSuccesses; private final int populationSize; private final int sampleSize; private double numericalVariance = Double.NaN; private boolean numericalVarianceIsCalculated = false; public HypergeometricDistribution(int populationSize, int numberOfSuccesses, int sampleSize) throws NotPositiveException, NotStrictlyPositiveException, NumberIsTooLargeException; public HypergeometricDistribution(RandomGenerator rng, int populationSize, int numberOfSuccesses, int sampleSize) throws NotPositiveException, NotStrictlyPositiveException, NumberIsTooLargeException; public double cumulativeProbability(int x); private int[] getDomain(int n, int m, int k); private int getLowerDomain(int n, int m, int k); public int getNumberOfSuccesses(); public int getPopulationSize(); public int getSampleSize(); private int getUpperDomain(int m, int k); public double probability(int x); public double upperCumulativeProbability(int x); private double innerCumulativeProbability(int x0, int x1, int dx); public double getNumericalMean(); public double getNumericalVariance(); protected double calculateNumericalVariance(); public int getSupportLowerBound(); public int getSupportUpperBound(); public boolean isSupportConnected(); } // Abstract Java Test Class package org.apache.commons.math3.distribution; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.exception.NotPositiveException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.util.Precision; import org.junit.Assert; import org.junit.Test; public class HypergeometricDistributionTest extends IntegerDistributionAbstractTest { @Override public IntegerDistribution makeDistribution(); @Override public int[] makeDensityTestPoints(); @Override public double[] makeDensityTestValues(); @Override public int[] makeCumulativeTestPoints(); @Override public double[] makeCumulativeTestValues(); @Override public double[] makeInverseCumulativeTestPoints(); @Override public int[] makeInverseCumulativeTestValues(); @Test public void testDegenerateNoFailures(); @Test public void testDegenerateNoSuccesses(); @Test public void testDegenerateFullSample(); @Test public void testPreconditions(); @Test public void testAccessors(); @Test public void testLargeValues(); private void testHypergeometricDistributionProbabilities(int populationSize, int sampleSize, int numberOfSucceses, double[][] data); @Test public void testMoreLargeValues(); @Test public void testMoments(); @Test public void testMath644(); @Test public void testMath1021(); } ``` You are a professional Java test case writer, please create a test case named `testDegenerateNoFailures` for the `HypergeometricDistribution` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** Verify that if there are no failures, mass is concentrated on sampleSize */ //-------------------- Additional test cases ------------------------------ @Test public void testDegenerateNoFailures() { ```
public class HypergeometricDistribution extends AbstractIntegerDistribution
package org.apache.commons.math3.distribution; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.exception.NotPositiveException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.util.Precision; import org.junit.Assert; import org.junit.Test;
@Override public IntegerDistribution makeDistribution(); @Override public int[] makeDensityTestPoints(); @Override public double[] makeDensityTestValues(); @Override public int[] makeCumulativeTestPoints(); @Override public double[] makeCumulativeTestValues(); @Override public double[] makeInverseCumulativeTestPoints(); @Override public int[] makeInverseCumulativeTestValues(); @Test public void testDegenerateNoFailures(); @Test public void testDegenerateNoSuccesses(); @Test public void testDegenerateFullSample(); @Test public void testPreconditions(); @Test public void testAccessors(); @Test public void testLargeValues(); private void testHypergeometricDistributionProbabilities(int populationSize, int sampleSize, int numberOfSucceses, double[][] data); @Test public void testMoreLargeValues(); @Test public void testMoments(); @Test public void testMath644(); @Test public void testMath1021();
8d3483cdda44403cfe04cfbe9aa2bbfab50dd771789967799f35c402c24f62c8
[ "org.apache.commons.math3.distribution.HypergeometricDistributionTest::testDegenerateNoFailures" ]
private static final long serialVersionUID = -436928820673516179L; private final int numberOfSuccesses; private final int populationSize; private final int sampleSize; private double numericalVariance = Double.NaN; private boolean numericalVarianceIsCalculated = false;
@Test public void testDegenerateNoFailures()
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.distribution; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.exception.NotPositiveException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.util.Precision; import org.junit.Assert; import org.junit.Test; /** * Test cases for HyperGeometriclDistribution. * Extends IntegerDistributionAbstractTest. See class javadoc for * IntegerDistributionAbstractTest for details. * * @version $Id$ */ public class HypergeometricDistributionTest extends IntegerDistributionAbstractTest { //-------------- Implementations for abstract methods ----------------------- /** Creates the default discrete distribution instance to use in tests. */ @Override public IntegerDistribution makeDistribution() { return new HypergeometricDistribution(10, 5, 5); } /** Creates the default probability density test input values */ @Override public int[] makeDensityTestPoints() { return new int[] {-1, 0, 1, 2, 3, 4, 5, 10}; } /** Creates the default probability density test expected values */ @Override public double[] makeDensityTestValues() { return new double[] {0d, 0.003968d, 0.099206d, 0.396825d, 0.396825d, 0.099206d, 0.003968d, 0d}; } /** Creates the default cumulative probability density test input values */ @Override public int[] makeCumulativeTestPoints() { return makeDensityTestPoints(); } /** Creates the default cumulative probability density test expected values */ @Override public double[] makeCumulativeTestValues() { return new double[] {0d, .003968d, .103175d, .50000d, .896825d, .996032d, 1.00000d, 1d}; } /** Creates the default inverse cumulative probability test input values */ @Override public double[] makeInverseCumulativeTestPoints() { return new double[] {0d, 0.001d, 0.010d, 0.025d, 0.050d, 0.100d, 0.999d, 0.990d, 0.975d, 0.950d, 0.900d, 1d}; } /** Creates the default inverse cumulative probability density test expected values */ @Override public int[] makeInverseCumulativeTestValues() { return new int[] {0, 0, 1, 1, 1, 1, 5, 4, 4, 4, 4, 5}; } //-------------------- Additional test cases ------------------------------ /** Verify that if there are no failures, mass is concentrated on sampleSize */ @Test public void testDegenerateNoFailures() { HypergeometricDistribution dist = new HypergeometricDistribution(5,5,3); setDistribution(dist); setCumulativeTestPoints(new int[] {-1, 0, 1, 3, 10 }); setCumulativeTestValues(new double[] {0d, 0d, 0d, 1d, 1d}); setDensityTestPoints(new int[] {-1, 0, 1, 3, 10}); setDensityTestValues(new double[] {0d, 0d, 0d, 1d, 0d}); setInverseCumulativeTestPoints(new double[] {0.1d, 0.5d}); setInverseCumulativeTestValues(new int[] {3, 3}); verifyDensities(); verifyCumulativeProbabilities(); verifyInverseCumulativeProbabilities(); Assert.assertEquals(dist.getSupportLowerBound(), 3); Assert.assertEquals(dist.getSupportUpperBound(), 3); } /** Verify that if there are no successes, mass is concentrated on 0 */ @Test public void testDegenerateNoSuccesses() { HypergeometricDistribution dist = new HypergeometricDistribution(5,0,3); setDistribution(dist); setCumulativeTestPoints(new int[] {-1, 0, 1, 3, 10 }); setCumulativeTestValues(new double[] {0d, 1d, 1d, 1d, 1d}); setDensityTestPoints(new int[] {-1, 0, 1, 3, 10}); setDensityTestValues(new double[] {0d, 1d, 0d, 0d, 0d}); setInverseCumulativeTestPoints(new double[] {0.1d, 0.5d}); setInverseCumulativeTestValues(new int[] {0, 0}); verifyDensities(); verifyCumulativeProbabilities(); verifyInverseCumulativeProbabilities(); Assert.assertEquals(dist.getSupportLowerBound(), 0); Assert.assertEquals(dist.getSupportUpperBound(), 0); } /** Verify that if sampleSize = populationSize, mass is concentrated on numberOfSuccesses */ @Test public void testDegenerateFullSample() { HypergeometricDistribution dist = new HypergeometricDistribution(5,3,5); setDistribution(dist); setCumulativeTestPoints(new int[] {-1, 0, 1, 3, 10 }); setCumulativeTestValues(new double[] {0d, 0d, 0d, 1d, 1d}); setDensityTestPoints(new int[] {-1, 0, 1, 3, 10}); setDensityTestValues(new double[] {0d, 0d, 0d, 1d, 0d}); setInverseCumulativeTestPoints(new double[] {0.1d, 0.5d}); setInverseCumulativeTestValues(new int[] {3, 3}); verifyDensities(); verifyCumulativeProbabilities(); verifyInverseCumulativeProbabilities(); Assert.assertEquals(dist.getSupportLowerBound(), 3); Assert.assertEquals(dist.getSupportUpperBound(), 3); } @Test public void testPreconditions() { try { new HypergeometricDistribution(0, 3, 5); Assert.fail("negative population size. NotStrictlyPositiveException expected"); } catch(NotStrictlyPositiveException ex) { // Expected. } try { new HypergeometricDistribution(5, -1, 5); Assert.fail("negative number of successes. NotPositiveException expected"); } catch(NotPositiveException ex) { // Expected. } try { new HypergeometricDistribution(5, 3, -1); Assert.fail("negative sample size. NotPositiveException expected"); } catch(NotPositiveException ex) { // Expected. } try { new HypergeometricDistribution(5, 6, 5); Assert.fail("numberOfSuccesses > populationSize. NumberIsTooLargeException expected"); } catch(NumberIsTooLargeException ex) { // Expected. } try { new HypergeometricDistribution(5, 3, 6); Assert.fail("sampleSize > populationSize. NumberIsTooLargeException expected"); } catch(NumberIsTooLargeException ex) { // Expected. } } @Test public void testAccessors() { HypergeometricDistribution dist = new HypergeometricDistribution(5, 3, 4); Assert.assertEquals(5, dist.getPopulationSize()); Assert.assertEquals(3, dist.getNumberOfSuccesses()); Assert.assertEquals(4, dist.getSampleSize()); } @Test public void testLargeValues() { int populationSize = 3456; int sampleSize = 789; int numberOfSucceses = 101; double[][] data = { {0.0, 2.75646034603961e-12, 2.75646034603961e-12, 1.0}, {1.0, 8.55705370142386e-11, 8.83269973602783e-11, 0.999999999997244}, {2.0, 1.31288129219665e-9, 1.40120828955693e-9, 0.999999999911673}, {3.0, 1.32724172984193e-8, 1.46736255879763e-8, 0.999999998598792}, {4.0, 9.94501711734089e-8, 1.14123796761385e-7, 0.999999985326375}, {5.0, 5.89080768883643e-7, 7.03204565645028e-7, 0.999999885876203}, {20.0, 0.0760051397707708, 0.27349758476299, 0.802507555007781}, {21.0, 0.087144222047629, 0.360641806810619, 0.72650241523701}, {22.0, 0.0940378846881819, 0.454679691498801, 0.639358193189381}, {23.0, 0.0956897500614809, 0.550369441560282, 0.545320308501199}, {24.0, 0.0919766921922999, 0.642346133752582, 0.449630558439718}, {25.0, 0.083641637261095, 0.725987771013677, 0.357653866247418}, {96.0, 5.93849188852098e-57, 1.0, 6.01900244560712e-57}, {97.0, 7.96593036832547e-59, 1.0, 8.05105570861321e-59}, {98.0, 8.44582921934367e-61, 1.0, 8.5125340287733e-61}, {99.0, 6.63604297068222e-63, 1.0, 6.670480942963e-63}, {100.0, 3.43501099007557e-65, 1.0, 3.4437972280786e-65}, {101.0, 8.78623800302957e-68, 1.0, 8.78623800302957e-68}, }; testHypergeometricDistributionProbabilities(populationSize, sampleSize, numberOfSucceses, data); } private void testHypergeometricDistributionProbabilities(int populationSize, int sampleSize, int numberOfSucceses, double[][] data) { HypergeometricDistribution dist = new HypergeometricDistribution(populationSize, numberOfSucceses, sampleSize); for (int i = 0; i < data.length; ++i) { int x = (int)data[i][0]; double pmf = data[i][1]; double actualPmf = dist.probability(x); TestUtils.assertRelativelyEquals("Expected equals for <"+x+"> pmf",pmf, actualPmf, 1.0e-9); double cdf = data[i][2]; double actualCdf = dist.cumulativeProbability(x); TestUtils.assertRelativelyEquals("Expected equals for <"+x+"> cdf",cdf, actualCdf, 1.0e-9); double cdf1 = data[i][3]; double actualCdf1 = dist.upperCumulativeProbability(x); TestUtils.assertRelativelyEquals("Expected equals for <"+x+"> cdf1",cdf1, actualCdf1, 1.0e-9); } } @Test public void testMoreLargeValues() { int populationSize = 26896; int sampleSize = 895; int numberOfSucceses = 55; double[][] data = { {0.0, 0.155168304750504, 0.155168304750504, 1.0}, {1.0, 0.29437545000746, 0.449543754757964, 0.844831695249496}, {2.0, 0.273841321577003, 0.723385076334967, 0.550456245242036}, {3.0, 0.166488572570786, 0.889873648905753, 0.276614923665033}, {4.0, 0.0743969744713231, 0.964270623377076, 0.110126351094247}, {5.0, 0.0260542785784855, 0.990324901955562, 0.0357293766229237}, {20.0, 3.57101101678792e-16, 1.0, 3.78252101622096e-16}, {21.0, 2.00551638598312e-17, 1.0, 2.11509999433041e-17}, {22.0, 1.04317070180562e-18, 1.0, 1.09583608347287e-18}, {23.0, 5.03153504903308e-20, 1.0, 5.266538166725e-20}, {24.0, 2.2525984149695e-21, 1.0, 2.35003117691919e-21}, {25.0, 9.3677424515947e-23, 1.0, 9.74327619496943e-23}, {50.0, 9.83633962945521e-69, 1.0, 9.8677629437617e-69}, {51.0, 3.13448949497553e-71, 1.0, 3.14233143064882e-71}, {52.0, 7.82755221928122e-74, 1.0, 7.84193567329055e-74}, {53.0, 1.43662126065532e-76, 1.0, 1.43834540093295e-76}, {54.0, 1.72312692517348e-79, 1.0, 1.7241402776278e-79}, {55.0, 1.01335245432581e-82, 1.0, 1.01335245432581e-82}, }; testHypergeometricDistributionProbabilities(populationSize, sampleSize, numberOfSucceses, data); } @Test public void testMoments() { final double tol = 1e-9; HypergeometricDistribution dist; dist = new HypergeometricDistribution(1500, 40, 100); Assert.assertEquals(dist.getNumericalMean(), 40d * 100d / 1500d, tol); Assert.assertEquals(dist.getNumericalVariance(), ( 100d * 40d * (1500d - 100d) * (1500d - 40d) ) / ( (1500d * 1500d * 1499d) ), tol); dist = new HypergeometricDistribution(3000, 55, 200); Assert.assertEquals(dist.getNumericalMean(), 55d * 200d / 3000d, tol); Assert.assertEquals(dist.getNumericalVariance(), ( 200d * 55d * (3000d - 200d) * (3000d - 55d) ) / ( (3000d * 3000d * 2999d) ), tol); } @Test public void testMath644() { int N = 14761461; // population int m = 1035; // successes in population int n = 1841; // number of trials int k = 0; final HypergeometricDistribution dist = new HypergeometricDistribution(N, m, n); Assert.assertTrue(Precision.compareTo(1.0, dist.upperCumulativeProbability(k), 1) == 0); Assert.assertTrue(Precision.compareTo(dist.cumulativeProbability(k), 0.0, 1) > 0); // another way to calculate the upper cumulative probability double upper = 1.0 - dist.cumulativeProbability(k) + dist.probability(k); Assert.assertTrue(Precision.compareTo(1.0, upper, 1) == 0); } @Test public void testMath1021() { final int N = 43130568; final int m = 42976365; final int n = 50; final HypergeometricDistribution dist = new HypergeometricDistribution(N, m, n); for (int i = 0; i < 100; i++) { final int sample = dist.sample(); Assert.assertTrue("sample=" + sample, 0 <= sample); Assert.assertTrue("sample=" + sample, sample <= n); } } }
[ { "be_test_class_file": "org/apache/commons/math3/distribution/HypergeometricDistribution.java", "be_test_class_name": "org.apache.commons.math3.distribution.HypergeometricDistribution", "be_test_function_name": "calculateNumericalVariance", "be_test_function_signature": "()D", "line_numbers": [ "292", "293", "294", "295" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/distribution/HypergeometricDistribution.java", "be_test_class_name": "org.apache.commons.math3.distribution.HypergeometricDistribution", "be_test_function_name": "cumulativeProbability", "be_test_function_signature": "(I)D", "line_numbers": [ "117", "118", "119", "120", "121", "123", "126" ], "method_line_rate": 0.8571428571428571 }, { "be_test_class_file": "org/apache/commons/math3/distribution/HypergeometricDistribution.java", "be_test_class_name": "org.apache.commons.math3.distribution.HypergeometricDistribution", "be_test_function_name": "getDomain", "be_test_function_signature": "(III)[I", "line_numbers": [ "139" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/distribution/HypergeometricDistribution.java", "be_test_class_name": "org.apache.commons.math3.distribution.HypergeometricDistribution", "be_test_function_name": "getLowerDomain", "be_test_function_signature": "(III)I", "line_numbers": [ "152" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/distribution/HypergeometricDistribution.java", "be_test_class_name": "org.apache.commons.math3.distribution.HypergeometricDistribution", "be_test_function_name": "getNumberOfSuccesses", "be_test_function_signature": "()I", "line_numbers": [ "161" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/distribution/HypergeometricDistribution.java", "be_test_class_name": "org.apache.commons.math3.distribution.HypergeometricDistribution", "be_test_function_name": "getNumericalMean", "be_test_function_signature": "()D", "line_numbers": [ "268" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/distribution/HypergeometricDistribution.java", "be_test_class_name": "org.apache.commons.math3.distribution.HypergeometricDistribution", "be_test_function_name": "getNumericalVariance", "be_test_function_signature": "()D", "line_numbers": [ "279", "280", "281", "283" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/distribution/HypergeometricDistribution.java", "be_test_class_name": "org.apache.commons.math3.distribution.HypergeometricDistribution", "be_test_function_name": "getPopulationSize", "be_test_function_signature": "()I", "line_numbers": [ "170" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/distribution/HypergeometricDistribution.java", "be_test_class_name": "org.apache.commons.math3.distribution.HypergeometricDistribution", "be_test_function_name": "getSampleSize", "be_test_function_signature": "()I", "line_numbers": [ "179" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/distribution/HypergeometricDistribution.java", "be_test_class_name": "org.apache.commons.math3.distribution.HypergeometricDistribution", "be_test_function_name": "getSupportLowerBound", "be_test_function_signature": "()I", "line_numbers": [ "308" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/distribution/HypergeometricDistribution.java", "be_test_class_name": "org.apache.commons.math3.distribution.HypergeometricDistribution", "be_test_function_name": "getSupportUpperBound", "be_test_function_signature": "()I", "line_numbers": [ "321" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/distribution/HypergeometricDistribution.java", "be_test_class_name": "org.apache.commons.math3.distribution.HypergeometricDistribution", "be_test_function_name": "getUpperDomain", "be_test_function_signature": "(II)I", "line_numbers": [ "191" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/distribution/HypergeometricDistribution.java", "be_test_class_name": "org.apache.commons.math3.distribution.HypergeometricDistribution", "be_test_function_name": "probability", "be_test_function_signature": "(I)D", "line_numbers": [ "198", "199", "200", "202", "203", "204", "206", "209", "211", "214" ], "method_line_rate": 1 } ]
public class SimplexSolverTest
@Test public void testModelWithNoArtificialVars() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2)); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3)); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 4)); SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MAXIMIZE, new NonNegativeConstraint(false)); Assert.assertEquals(2.0, solution.getPoint()[0], 0.0); Assert.assertEquals(2.0, solution.getPoint()[1], 0.0); Assert.assertEquals(50.0, solution.getValue(), 0.0); }
// // Abstract Java Tested Class // package org.apache.commons.math3.optim.linear; // // import java.util.ArrayList; // import java.util.List; // import org.apache.commons.math3.exception.TooManyIterationsException; // import org.apache.commons.math3.optim.PointValuePair; // import org.apache.commons.math3.util.Precision; // // // // public class SimplexSolver extends LinearOptimizer { // static final int DEFAULT_ULPS = 10; // static final double DEFAULT_CUT_OFF = 1e-12; // private static final double DEFAULT_EPSILON = 1.0e-6; // private final double epsilon; // private final int maxUlps; // private final double cutOff; // // public SimplexSolver(); // public SimplexSolver(final double epsilon); // public SimplexSolver(final double epsilon, final int maxUlps); // public SimplexSolver(final double epsilon, final int maxUlps, final double cutOff); // private Integer getPivotColumn(SimplexTableau tableau); // private Integer getPivotRow(SimplexTableau tableau, final int col); // protected void doIteration(final SimplexTableau tableau) // throws TooManyIterationsException, // UnboundedSolutionException; // protected void solvePhase1(final SimplexTableau tableau) // throws TooManyIterationsException, // UnboundedSolutionException, // NoFeasibleSolutionException; // @Override // public PointValuePair doOptimize() // throws TooManyIterationsException, // UnboundedSolutionException, // NoFeasibleSolutionException; // } // // // Abstract Java Test Class // package org.apache.commons.math3.optim.linear; // // import java.util.ArrayList; // import java.util.Collection; // import java.util.List; // import org.apache.commons.math3.optim.MaxIter; // import org.apache.commons.math3.optim.nonlinear.scalar.GoalType; // import org.apache.commons.math3.optim.PointValuePair; // import org.apache.commons.math3.util.Precision; // import org.junit.Test; // import org.junit.Assert; // // // // public class SimplexSolverTest { // private static final MaxIter DEFAULT_MAX_ITER = new MaxIter(100); // // @Test // public void testMath828(); // @Test // public void testMath828Cycle(); // @Test // public void testMath781(); // @Test // public void testMath713NegativeVariable(); // @Test // public void testMath434NegativeVariable(); // @Test(expected = NoFeasibleSolutionException.class) // public void testMath434UnfeasibleSolution(); // @Test // public void testMath434PivotRowSelection(); // @Test // public void testMath434PivotRowSelection2(); // @Test // public void testMath272(); // @Test // public void testMath286(); // @Test // public void testDegeneracy(); // @Test // public void testMath288(); // @Test // public void testMath290GEQ(); // @Test(expected=NoFeasibleSolutionException.class) // public void testMath290LEQ(); // @Test // public void testMath293(); // @Test // public void testMath930(); // @Test // public void testSimplexSolver(); // @Test // public void testSingleVariableAndConstraint(); // @Test // public void testModelWithNoArtificialVars(); // @Test // public void testMinimization(); // @Test // public void testSolutionWithNegativeDecisionVariable(); // @Test(expected = NoFeasibleSolutionException.class) // public void testInfeasibleSolution(); // @Test(expected = UnboundedSolutionException.class) // public void testUnboundedSolution(); // @Test // public void testRestrictVariablesToNonNegative(); // @Test // public void testEpsilon(); // @Test // public void testTrivialModel(); // @Test // public void testLargeModel(); // private LinearConstraint equationFromString(int numCoefficients, String s); // private static boolean validSolution(PointValuePair solution, List<LinearConstraint> constraints, double epsilon); // } // You are a professional Java test case writer, please create a test case named `testModelWithNoArtificialVars` for the `SimplexSolver` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * With no artificial variables needed (no equals and no greater than * constraints) we can go straight to Phase 2. */
src/test/java/org/apache/commons/math3/optim/linear/SimplexSolverTest.java
package org.apache.commons.math3.optim.linear; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.exception.TooManyIterationsException; import org.apache.commons.math3.optim.PointValuePair; import org.apache.commons.math3.util.Precision;
public SimplexSolver(); public SimplexSolver(final double epsilon); public SimplexSolver(final double epsilon, final int maxUlps); public SimplexSolver(final double epsilon, final int maxUlps, final double cutOff); private Integer getPivotColumn(SimplexTableau tableau); private Integer getPivotRow(SimplexTableau tableau, final int col); protected void doIteration(final SimplexTableau tableau) throws TooManyIterationsException, UnboundedSolutionException; protected void solvePhase1(final SimplexTableau tableau) throws TooManyIterationsException, UnboundedSolutionException, NoFeasibleSolutionException; @Override public PointValuePair doOptimize() throws TooManyIterationsException, UnboundedSolutionException, NoFeasibleSolutionException;
477
testModelWithNoArtificialVars
```java // Abstract Java Tested Class package org.apache.commons.math3.optim.linear; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.exception.TooManyIterationsException; import org.apache.commons.math3.optim.PointValuePair; import org.apache.commons.math3.util.Precision; public class SimplexSolver extends LinearOptimizer { static final int DEFAULT_ULPS = 10; static final double DEFAULT_CUT_OFF = 1e-12; private static final double DEFAULT_EPSILON = 1.0e-6; private final double epsilon; private final int maxUlps; private final double cutOff; public SimplexSolver(); public SimplexSolver(final double epsilon); public SimplexSolver(final double epsilon, final int maxUlps); public SimplexSolver(final double epsilon, final int maxUlps, final double cutOff); private Integer getPivotColumn(SimplexTableau tableau); private Integer getPivotRow(SimplexTableau tableau, final int col); protected void doIteration(final SimplexTableau tableau) throws TooManyIterationsException, UnboundedSolutionException; protected void solvePhase1(final SimplexTableau tableau) throws TooManyIterationsException, UnboundedSolutionException, NoFeasibleSolutionException; @Override public PointValuePair doOptimize() throws TooManyIterationsException, UnboundedSolutionException, NoFeasibleSolutionException; } // Abstract Java Test Class package org.apache.commons.math3.optim.linear; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.commons.math3.optim.MaxIter; import org.apache.commons.math3.optim.nonlinear.scalar.GoalType; import org.apache.commons.math3.optim.PointValuePair; import org.apache.commons.math3.util.Precision; import org.junit.Test; import org.junit.Assert; public class SimplexSolverTest { private static final MaxIter DEFAULT_MAX_ITER = new MaxIter(100); @Test public void testMath828(); @Test public void testMath828Cycle(); @Test public void testMath781(); @Test public void testMath713NegativeVariable(); @Test public void testMath434NegativeVariable(); @Test(expected = NoFeasibleSolutionException.class) public void testMath434UnfeasibleSolution(); @Test public void testMath434PivotRowSelection(); @Test public void testMath434PivotRowSelection2(); @Test public void testMath272(); @Test public void testMath286(); @Test public void testDegeneracy(); @Test public void testMath288(); @Test public void testMath290GEQ(); @Test(expected=NoFeasibleSolutionException.class) public void testMath290LEQ(); @Test public void testMath293(); @Test public void testMath930(); @Test public void testSimplexSolver(); @Test public void testSingleVariableAndConstraint(); @Test public void testModelWithNoArtificialVars(); @Test public void testMinimization(); @Test public void testSolutionWithNegativeDecisionVariable(); @Test(expected = NoFeasibleSolutionException.class) public void testInfeasibleSolution(); @Test(expected = UnboundedSolutionException.class) public void testUnboundedSolution(); @Test public void testRestrictVariablesToNonNegative(); @Test public void testEpsilon(); @Test public void testTrivialModel(); @Test public void testLargeModel(); private LinearConstraint equationFromString(int numCoefficients, String s); private static boolean validSolution(PointValuePair solution, List<LinearConstraint> constraints, double epsilon); } ``` You are a professional Java test case writer, please create a test case named `testModelWithNoArtificialVars` for the `SimplexSolver` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * With no artificial variables needed (no equals and no greater than * constraints) we can go straight to Phase 2. */
463
// // Abstract Java Tested Class // package org.apache.commons.math3.optim.linear; // // import java.util.ArrayList; // import java.util.List; // import org.apache.commons.math3.exception.TooManyIterationsException; // import org.apache.commons.math3.optim.PointValuePair; // import org.apache.commons.math3.util.Precision; // // // // public class SimplexSolver extends LinearOptimizer { // static final int DEFAULT_ULPS = 10; // static final double DEFAULT_CUT_OFF = 1e-12; // private static final double DEFAULT_EPSILON = 1.0e-6; // private final double epsilon; // private final int maxUlps; // private final double cutOff; // // public SimplexSolver(); // public SimplexSolver(final double epsilon); // public SimplexSolver(final double epsilon, final int maxUlps); // public SimplexSolver(final double epsilon, final int maxUlps, final double cutOff); // private Integer getPivotColumn(SimplexTableau tableau); // private Integer getPivotRow(SimplexTableau tableau, final int col); // protected void doIteration(final SimplexTableau tableau) // throws TooManyIterationsException, // UnboundedSolutionException; // protected void solvePhase1(final SimplexTableau tableau) // throws TooManyIterationsException, // UnboundedSolutionException, // NoFeasibleSolutionException; // @Override // public PointValuePair doOptimize() // throws TooManyIterationsException, // UnboundedSolutionException, // NoFeasibleSolutionException; // } // // // Abstract Java Test Class // package org.apache.commons.math3.optim.linear; // // import java.util.ArrayList; // import java.util.Collection; // import java.util.List; // import org.apache.commons.math3.optim.MaxIter; // import org.apache.commons.math3.optim.nonlinear.scalar.GoalType; // import org.apache.commons.math3.optim.PointValuePair; // import org.apache.commons.math3.util.Precision; // import org.junit.Test; // import org.junit.Assert; // // // // public class SimplexSolverTest { // private static final MaxIter DEFAULT_MAX_ITER = new MaxIter(100); // // @Test // public void testMath828(); // @Test // public void testMath828Cycle(); // @Test // public void testMath781(); // @Test // public void testMath713NegativeVariable(); // @Test // public void testMath434NegativeVariable(); // @Test(expected = NoFeasibleSolutionException.class) // public void testMath434UnfeasibleSolution(); // @Test // public void testMath434PivotRowSelection(); // @Test // public void testMath434PivotRowSelection2(); // @Test // public void testMath272(); // @Test // public void testMath286(); // @Test // public void testDegeneracy(); // @Test // public void testMath288(); // @Test // public void testMath290GEQ(); // @Test(expected=NoFeasibleSolutionException.class) // public void testMath290LEQ(); // @Test // public void testMath293(); // @Test // public void testMath930(); // @Test // public void testSimplexSolver(); // @Test // public void testSingleVariableAndConstraint(); // @Test // public void testModelWithNoArtificialVars(); // @Test // public void testMinimization(); // @Test // public void testSolutionWithNegativeDecisionVariable(); // @Test(expected = NoFeasibleSolutionException.class) // public void testInfeasibleSolution(); // @Test(expected = UnboundedSolutionException.class) // public void testUnboundedSolution(); // @Test // public void testRestrictVariablesToNonNegative(); // @Test // public void testEpsilon(); // @Test // public void testTrivialModel(); // @Test // public void testLargeModel(); // private LinearConstraint equationFromString(int numCoefficients, String s); // private static boolean validSolution(PointValuePair solution, List<LinearConstraint> constraints, double epsilon); // } // You are a professional Java test case writer, please create a test case named `testModelWithNoArtificialVars` for the `SimplexSolver` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * With no artificial variables needed (no equals and no greater than * constraints) we can go straight to Phase 2. */ @Test public void testModelWithNoArtificialVars() {
/** * With no artificial variables needed (no equals and no greater than * constraints) we can go straight to Phase 2. */
1
org.apache.commons.math3.optim.linear.SimplexSolver
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.math3.optim.linear; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.exception.TooManyIterationsException; import org.apache.commons.math3.optim.PointValuePair; import org.apache.commons.math3.util.Precision; public class SimplexSolver extends LinearOptimizer { static final int DEFAULT_ULPS = 10; static final double DEFAULT_CUT_OFF = 1e-12; private static final double DEFAULT_EPSILON = 1.0e-6; private final double epsilon; private final int maxUlps; private final double cutOff; public SimplexSolver(); public SimplexSolver(final double epsilon); public SimplexSolver(final double epsilon, final int maxUlps); public SimplexSolver(final double epsilon, final int maxUlps, final double cutOff); private Integer getPivotColumn(SimplexTableau tableau); private Integer getPivotRow(SimplexTableau tableau, final int col); protected void doIteration(final SimplexTableau tableau) throws TooManyIterationsException, UnboundedSolutionException; protected void solvePhase1(final SimplexTableau tableau) throws TooManyIterationsException, UnboundedSolutionException, NoFeasibleSolutionException; @Override public PointValuePair doOptimize() throws TooManyIterationsException, UnboundedSolutionException, NoFeasibleSolutionException; } // Abstract Java Test Class package org.apache.commons.math3.optim.linear; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.commons.math3.optim.MaxIter; import org.apache.commons.math3.optim.nonlinear.scalar.GoalType; import org.apache.commons.math3.optim.PointValuePair; import org.apache.commons.math3.util.Precision; import org.junit.Test; import org.junit.Assert; public class SimplexSolverTest { private static final MaxIter DEFAULT_MAX_ITER = new MaxIter(100); @Test public void testMath828(); @Test public void testMath828Cycle(); @Test public void testMath781(); @Test public void testMath713NegativeVariable(); @Test public void testMath434NegativeVariable(); @Test(expected = NoFeasibleSolutionException.class) public void testMath434UnfeasibleSolution(); @Test public void testMath434PivotRowSelection(); @Test public void testMath434PivotRowSelection2(); @Test public void testMath272(); @Test public void testMath286(); @Test public void testDegeneracy(); @Test public void testMath288(); @Test public void testMath290GEQ(); @Test(expected=NoFeasibleSolutionException.class) public void testMath290LEQ(); @Test public void testMath293(); @Test public void testMath930(); @Test public void testSimplexSolver(); @Test public void testSingleVariableAndConstraint(); @Test public void testModelWithNoArtificialVars(); @Test public void testMinimization(); @Test public void testSolutionWithNegativeDecisionVariable(); @Test(expected = NoFeasibleSolutionException.class) public void testInfeasibleSolution(); @Test(expected = UnboundedSolutionException.class) public void testUnboundedSolution(); @Test public void testRestrictVariablesToNonNegative(); @Test public void testEpsilon(); @Test public void testTrivialModel(); @Test public void testLargeModel(); private LinearConstraint equationFromString(int numCoefficients, String s); private static boolean validSolution(PointValuePair solution, List<LinearConstraint> constraints, double epsilon); } ``` You are a professional Java test case writer, please create a test case named `testModelWithNoArtificialVars` for the `SimplexSolver` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * With no artificial variables needed (no equals and no greater than * constraints) we can go straight to Phase 2. */ @Test public void testModelWithNoArtificialVars() { ```
public class SimplexSolver extends LinearOptimizer
package org.apache.commons.math3.optim.linear; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.commons.math3.optim.MaxIter; import org.apache.commons.math3.optim.nonlinear.scalar.GoalType; import org.apache.commons.math3.optim.PointValuePair; import org.apache.commons.math3.util.Precision; import org.junit.Test; import org.junit.Assert;
@Test public void testMath828(); @Test public void testMath828Cycle(); @Test public void testMath781(); @Test public void testMath713NegativeVariable(); @Test public void testMath434NegativeVariable(); @Test(expected = NoFeasibleSolutionException.class) public void testMath434UnfeasibleSolution(); @Test public void testMath434PivotRowSelection(); @Test public void testMath434PivotRowSelection2(); @Test public void testMath272(); @Test public void testMath286(); @Test public void testDegeneracy(); @Test public void testMath288(); @Test public void testMath290GEQ(); @Test(expected=NoFeasibleSolutionException.class) public void testMath290LEQ(); @Test public void testMath293(); @Test public void testMath930(); @Test public void testSimplexSolver(); @Test public void testSingleVariableAndConstraint(); @Test public void testModelWithNoArtificialVars(); @Test public void testMinimization(); @Test public void testSolutionWithNegativeDecisionVariable(); @Test(expected = NoFeasibleSolutionException.class) public void testInfeasibleSolution(); @Test(expected = UnboundedSolutionException.class) public void testUnboundedSolution(); @Test public void testRestrictVariablesToNonNegative(); @Test public void testEpsilon(); @Test public void testTrivialModel(); @Test public void testLargeModel(); private LinearConstraint equationFromString(int numCoefficients, String s); private static boolean validSolution(PointValuePair solution, List<LinearConstraint> constraints, double epsilon);
93b96a9cfc5f2a11892e28d29632c7b5d38a5a0e1cd31b654412ee6958484b25
[ "org.apache.commons.math3.optim.linear.SimplexSolverTest::testModelWithNoArtificialVars" ]
static final int DEFAULT_ULPS = 10; static final double DEFAULT_CUT_OFF = 1e-12; private static final double DEFAULT_EPSILON = 1.0e-6; private final double epsilon; private final int maxUlps; private final double cutOff;
@Test public void testModelWithNoArtificialVars()
private static final MaxIter DEFAULT_MAX_ITER = new MaxIter(100);
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.linear; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.commons.math3.optim.MaxIter; import org.apache.commons.math3.optim.nonlinear.scalar.GoalType; import org.apache.commons.math3.optim.PointValuePair; import org.apache.commons.math3.util.Precision; import org.junit.Test; import org.junit.Assert; public class SimplexSolverTest { private static final MaxIter DEFAULT_MAX_ITER = new MaxIter(100); @Test public void testMath828() { LinearObjectiveFunction f = new LinearObjectiveFunction( new double[] { 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, 0.0); ArrayList <LinearConstraint>constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] {0.0, 39.0, 23.0, 96.0, 15.0, 48.0, 9.0, 21.0, 48.0, 36.0, 76.0, 19.0, 88.0, 17.0, 16.0, 36.0,}, Relationship.GEQ, 15.0)); constraints.add(new LinearConstraint(new double[] {0.0, 59.0, 93.0, 12.0, 29.0, 78.0, 73.0, 87.0, 32.0, 70.0, 68.0, 24.0, 11.0, 26.0, 65.0, 25.0,}, Relationship.GEQ, 29.0)); constraints.add(new LinearConstraint(new double[] {0.0, 74.0, 5.0, 82.0, 6.0, 97.0, 55.0, 44.0, 52.0, 54.0, 5.0, 93.0, 91.0, 8.0, 20.0, 97.0,}, Relationship.GEQ, 6.0)); constraints.add(new LinearConstraint(new double[] {8.0, -3.0, -28.0, -72.0, -8.0, -31.0, -31.0, -74.0, -47.0, -59.0, -24.0, -57.0, -56.0, -16.0, -92.0, -59.0,}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {25.0, -7.0, -99.0, -78.0, -25.0, -14.0, -16.0, -89.0, -39.0, -56.0, -53.0, -9.0, -18.0, -26.0, -11.0, -61.0,}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {33.0, -95.0, -15.0, -4.0, -33.0, -3.0, -20.0, -96.0, -27.0, -13.0, -80.0, -24.0, -3.0, -13.0, -57.0, -76.0,}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {7.0, -95.0, -39.0, -93.0, -7.0, -94.0, -94.0, -62.0, -76.0, -26.0, -53.0, -57.0, -31.0, -76.0, -53.0, -52.0,}, Relationship.GEQ, 0.0)); double epsilon = 1e-6; PointValuePair solution = new SimplexSolver().optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MINIMIZE, new NonNegativeConstraint(true)); Assert.assertEquals(1.0d, solution.getValue(), epsilon); Assert.assertTrue(validSolution(solution, constraints, epsilon)); } @Test public void testMath828Cycle() { LinearObjectiveFunction f = new LinearObjectiveFunction( new double[] { 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, 0.0); ArrayList <LinearConstraint>constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] {0.0, 16.0, 14.0, 69.0, 1.0, 85.0, 52.0, 43.0, 64.0, 97.0, 14.0, 74.0, 89.0, 28.0, 94.0, 58.0, 13.0, 22.0, 21.0, 17.0, 30.0, 25.0, 1.0, 59.0, 91.0, 78.0, 12.0, 74.0, 56.0, 3.0, 88.0,}, Relationship.GEQ, 91.0)); constraints.add(new LinearConstraint(new double[] {0.0, 60.0, 40.0, 81.0, 71.0, 72.0, 46.0, 45.0, 38.0, 48.0, 40.0, 17.0, 33.0, 85.0, 64.0, 32.0, 84.0, 3.0, 54.0, 44.0, 71.0, 67.0, 90.0, 95.0, 54.0, 99.0, 99.0, 29.0, 52.0, 98.0, 9.0,}, Relationship.GEQ, 54.0)); constraints.add(new LinearConstraint(new double[] {0.0, 41.0, 12.0, 86.0, 90.0, 61.0, 31.0, 41.0, 23.0, 89.0, 17.0, 74.0, 44.0, 27.0, 16.0, 47.0, 80.0, 32.0, 11.0, 56.0, 68.0, 82.0, 11.0, 62.0, 62.0, 53.0, 39.0, 16.0, 48.0, 1.0, 63.0,}, Relationship.GEQ, 62.0)); constraints.add(new LinearConstraint(new double[] {83.0, -76.0, -94.0, -19.0, -15.0, -70.0, -72.0, -57.0, -63.0, -65.0, -22.0, -94.0, -22.0, -88.0, -86.0, -89.0, -72.0, -16.0, -80.0, -49.0, -70.0, -93.0, -95.0, -17.0, -83.0, -97.0, -31.0, -47.0, -31.0, -13.0, -23.0,}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {41.0, -96.0, -41.0, -48.0, -70.0, -43.0, -43.0, -43.0, -97.0, -37.0, -85.0, -70.0, -45.0, -67.0, -87.0, -69.0, -94.0, -54.0, -54.0, -92.0, -79.0, -10.0, -35.0, -20.0, -41.0, -41.0, -65.0, -25.0, -12.0, -8.0, -46.0,}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {27.0, -42.0, -65.0, -49.0, -53.0, -42.0, -17.0, -2.0, -61.0, -31.0, -76.0, -47.0, -8.0, -93.0, -86.0, -62.0, -65.0, -63.0, -22.0, -43.0, -27.0, -23.0, -32.0, -74.0, -27.0, -63.0, -47.0, -78.0, -29.0, -95.0, -73.0,}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {15.0, -46.0, -41.0, -83.0, -98.0, -99.0, -21.0, -35.0, -7.0, -14.0, -80.0, -63.0, -18.0, -42.0, -5.0, -34.0, -56.0, -70.0, -16.0, -18.0, -74.0, -61.0, -47.0, -41.0, -15.0, -79.0, -18.0, -47.0, -88.0, -68.0, -55.0,}, Relationship.GEQ, 0.0)); double epsilon = 1e-6; PointValuePair solution = new SimplexSolver().optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MINIMIZE, new NonNegativeConstraint(true)); Assert.assertEquals(1.0d, solution.getValue(), epsilon); Assert.assertTrue(validSolution(solution, constraints, epsilon)); } @Test public void testMath781() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 2, 6, 7 }, 0); ArrayList<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 2, 1 }, Relationship.LEQ, 2)); constraints.add(new LinearConstraint(new double[] { -1, 1, 1 }, Relationship.LEQ, -1)); constraints.add(new LinearConstraint(new double[] { 2, -3, 1 }, Relationship.LEQ, -1)); double epsilon = 1e-6; SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MAXIMIZE, new NonNegativeConstraint(false)); Assert.assertTrue(Precision.compareTo(solution.getPoint()[0], 0.0d, epsilon) > 0); Assert.assertTrue(Precision.compareTo(solution.getPoint()[1], 0.0d, epsilon) > 0); Assert.assertTrue(Precision.compareTo(solution.getPoint()[2], 0.0d, epsilon) < 0); Assert.assertEquals(2.0d, solution.getValue(), epsilon); } @Test public void testMath713NegativeVariable() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {1.0, 1.0}, 0.0d); ArrayList<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] {1, 0}, Relationship.EQ, 1)); double epsilon = 1e-6; SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MINIMIZE, new NonNegativeConstraint(true)); Assert.assertTrue(Precision.compareTo(solution.getPoint()[0], 0.0d, epsilon) >= 0); Assert.assertTrue(Precision.compareTo(solution.getPoint()[1], 0.0d, epsilon) >= 0); } @Test public void testMath434NegativeVariable() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {0.0, 0.0, 1.0}, 0.0d); ArrayList<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] {1, 1, 0}, Relationship.EQ, 5)); constraints.add(new LinearConstraint(new double[] {0, 0, 1}, Relationship.GEQ, -10)); double epsilon = 1e-6; SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MINIMIZE, new NonNegativeConstraint(false)); Assert.assertEquals(5.0, solution.getPoint()[0] + solution.getPoint()[1], epsilon); Assert.assertEquals(-10.0, solution.getPoint()[2], epsilon); Assert.assertEquals(-10.0, solution.getValue(), epsilon); } @Test(expected = NoFeasibleSolutionException.class) public void testMath434UnfeasibleSolution() { double epsilon = 1e-6; LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {1.0, 0.0}, 0.0); ArrayList<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] {epsilon/2, 0.5}, Relationship.EQ, 0)); constraints.add(new LinearConstraint(new double[] {1e-3, 0.1}, Relationship.EQ, 10)); SimplexSolver solver = new SimplexSolver(); // allowing only non-negative values, no feasible solution shall be found solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MINIMIZE, new NonNegativeConstraint(true)); } @Test public void testMath434PivotRowSelection() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {1.0}, 0.0); double epsilon = 1e-6; ArrayList<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] {200}, Relationship.GEQ, 1)); constraints.add(new LinearConstraint(new double[] {100}, Relationship.GEQ, 0.499900001)); SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MINIMIZE, new NonNegativeConstraint(false)); Assert.assertTrue(Precision.compareTo(solution.getPoint()[0] * 200.d, 1.d, epsilon) >= 0); Assert.assertEquals(0.0050, solution.getValue(), epsilon); } @Test public void testMath434PivotRowSelection2() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] {0.0d, 1.0d, 1.0d, 0.0d, 0.0d, 0.0d, 0.0d}, 0.0d); ArrayList<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] {1.0d, -0.1d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d}, Relationship.EQ, -0.1d)); constraints.add(new LinearConstraint(new double[] {1.0d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, -1e-18d)); constraints.add(new LinearConstraint(new double[] {0.0d, 1.0d, 0.0d, 0.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d)); constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 0.0d, 1.0d, 0.0d, -0.0128588d, 1e-5d}, Relationship.EQ, 0.0d)); constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 0.0d, 0.0d, 1.0d, 1e-5d, -0.0128586d}, Relationship.EQ, 1e-10d)); constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, -1.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d)); constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, 1.0d, 0.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d)); constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, 0.0d, -1.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d)); constraints.add(new LinearConstraint(new double[] {0.0d, 0.0d, 1.0d, 0.0d, 1.0d, 0.0d, 0.0d}, Relationship.GEQ, 0.0d)); double epsilon = 1e-7; SimplexSolver simplex = new SimplexSolver(); PointValuePair solution = simplex.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MINIMIZE, new NonNegativeConstraint(false)); Assert.assertTrue(Precision.compareTo(solution.getPoint()[0], -1e-18d, epsilon) >= 0); Assert.assertEquals(1.0d, solution.getPoint()[1], epsilon); Assert.assertEquals(0.0d, solution.getPoint()[2], epsilon); Assert.assertEquals(1.0d, solution.getValue(), epsilon); } @Test public void testMath272() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 2, 2, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1, 0 }, Relationship.GEQ, 1)); constraints.add(new LinearConstraint(new double[] { 1, 0, 1 }, Relationship.GEQ, 1)); constraints.add(new LinearConstraint(new double[] { 0, 1, 0 }, Relationship.GEQ, 1)); SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MINIMIZE, new NonNegativeConstraint(true)); Assert.assertEquals(0.0, solution.getPoint()[0], .0000001); Assert.assertEquals(1.0, solution.getPoint()[1], .0000001); Assert.assertEquals(1.0, solution.getPoint()[2], .0000001); Assert.assertEquals(3.0, solution.getValue(), .0000001); } @Test public void testMath286() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.6, 0.4 }, 0 ); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 23.0)); constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 23.0)); constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0, 0, 0 }, Relationship.GEQ, 10.0)); constraints.add(new LinearConstraint(new double[] { 0, 0, 1, 0, 0, 0 }, Relationship.GEQ, 8.0)); constraints.add(new LinearConstraint(new double[] { 0, 0, 0, 0, 1, 0 }, Relationship.GEQ, 5.0)); SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MAXIMIZE, new NonNegativeConstraint(true)); Assert.assertEquals(25.8, solution.getValue(), .0000001); Assert.assertEquals(23.0, solution.getPoint()[0] + solution.getPoint()[2] + solution.getPoint()[4], 0.0000001); Assert.assertEquals(23.0, solution.getPoint()[1] + solution.getPoint()[3] + solution.getPoint()[5], 0.0000001); Assert.assertTrue(solution.getPoint()[0] >= 10.0 - 0.0000001); Assert.assertTrue(solution.getPoint()[2] >= 8.0 - 0.0000001); Assert.assertTrue(solution.getPoint()[4] >= 5.0 - 0.0000001); } @Test public void testDegeneracy() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.7 }, 0 ); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 18.0)); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.GEQ, 10.0)); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, 8.0)); SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MINIMIZE, new NonNegativeConstraint(true)); Assert.assertEquals(13.6, solution.getValue(), .0000001); } @Test public void testMath288() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 7, 3, 0, 0 }, 0 ); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 3, 0, -5, 0 }, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] { 2, 0, 0, -5 }, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] { 0, 3, 0, -5 }, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] { 1, 0, 0, 0 }, Relationship.LEQ, 1.0)); constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 0 }, Relationship.LEQ, 1.0)); SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MAXIMIZE, new NonNegativeConstraint(true)); Assert.assertEquals(10.0, solution.getValue(), .0000001); } @Test public void testMath290GEQ() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 5 }, 0 ); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 2, 0 }, Relationship.GEQ, -1.0)); SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MINIMIZE, new NonNegativeConstraint(true)); Assert.assertEquals(0, solution.getValue(), .0000001); Assert.assertEquals(0, solution.getPoint()[0], .0000001); Assert.assertEquals(0, solution.getPoint()[1], .0000001); } @Test(expected=NoFeasibleSolutionException.class) public void testMath290LEQ() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 5 }, 0 ); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 2, 0 }, Relationship.LEQ, -1.0)); SimplexSolver solver = new SimplexSolver(); solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MINIMIZE, new NonNegativeConstraint(true)); } @Test public void testMath293() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.4, 0.6}, 0 ); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 30.0)); constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 30.0)); constraints.add(new LinearConstraint(new double[] { 0.8, 0.2, 0.0, 0.0, 0.0, 0.0 }, Relationship.GEQ, 10.0)); constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.7, 0.3, 0.0, 0.0 }, Relationship.GEQ, 10.0)); constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.0, 0.0, 0.4, 0.6 }, Relationship.GEQ, 10.0)); SimplexSolver solver = new SimplexSolver(); PointValuePair solution1 = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MAXIMIZE, new NonNegativeConstraint(true)); Assert.assertEquals(15.7143, solution1.getPoint()[0], .0001); Assert.assertEquals(0.0, solution1.getPoint()[1], .0001); Assert.assertEquals(14.2857, solution1.getPoint()[2], .0001); Assert.assertEquals(0.0, solution1.getPoint()[3], .0001); Assert.assertEquals(0.0, solution1.getPoint()[4], .0001); Assert.assertEquals(30.0, solution1.getPoint()[5], .0001); Assert.assertEquals(40.57143, solution1.getValue(), .0001); double valA = 0.8 * solution1.getPoint()[0] + 0.2 * solution1.getPoint()[1]; double valB = 0.7 * solution1.getPoint()[2] + 0.3 * solution1.getPoint()[3]; double valC = 0.4 * solution1.getPoint()[4] + 0.6 * solution1.getPoint()[5]; f = new LinearObjectiveFunction(new double[] { 0.8, 0.2, 0.7, 0.3, 0.4, 0.6}, 0 ); constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0, 1, 0, 1, 0 }, Relationship.EQ, 30.0)); constraints.add(new LinearConstraint(new double[] { 0, 1, 0, 1, 0, 1 }, Relationship.EQ, 30.0)); constraints.add(new LinearConstraint(new double[] { 0.8, 0.2, 0.0, 0.0, 0.0, 0.0 }, Relationship.GEQ, valA)); constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.7, 0.3, 0.0, 0.0 }, Relationship.GEQ, valB)); constraints.add(new LinearConstraint(new double[] { 0.0, 0.0, 0.0, 0.0, 0.4, 0.6 }, Relationship.GEQ, valC)); PointValuePair solution2 = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MAXIMIZE, new NonNegativeConstraint(true)); Assert.assertEquals(40.57143, solution2.getValue(), .0001); } @Test public void testMath930() { Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] {1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 1, 0, -1, 0, -1, 0, 1, 0, -1, 0, 1, 0, 1, 0, -1, 0, -1, 0, 1, 0, 1, 0, -1, 0, 1, 0, -1, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.628803}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.676993}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 1, -1, 0, 0, -1, 1, 0, 0, -1, 1, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, 1, -1, 0, 0, 1, -1, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.136677}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.444434}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.254028}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.302218}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, -1, 1, 1, -1, 0, 0, 0, 0, -1, 1, 1, -1, 0, 0, 0, 0, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.653981}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.690437}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.423786}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.486717}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 0, 0, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.049232}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.304747}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.129826}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.205625}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, -1, 1, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 1, -1, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.621944}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.764385}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 1, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.432572}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.480762}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.055983}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.11378}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.009607}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.057797}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.407308}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.452749}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.269677}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.321806}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.049232}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.06902}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.028754}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.484254}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.524607}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, -1, 0, 1, 0, -1, 0, 1, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.385492}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.430134}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, -1, 1, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.34983}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.375781}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.254028}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.281308}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.304995}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.345347}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.288899}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.332212}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, 0, 0, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.14351}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.17057}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, -0.129826}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, -0.157435}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, -1, 1, 1, -1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, -1}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, -1, 0, 1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, -0.141071}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, -0.232574}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, 0, -1, 1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, -0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, -1}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, -0.009607}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, -0.057797}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, -1, 1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, -0.091644}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, -0.203531}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0}, Relationship.GEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -0.028754}, Relationship.LEQ, 0.0)); constraints.add(new LinearConstraint(new double[] {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, Relationship.EQ, 1.0)); double[] objFunctionCoeff = new double[33]; objFunctionCoeff[3] = 1; LinearObjectiveFunction f = new LinearObjectiveFunction(objFunctionCoeff, 0); SimplexSolver solver = new SimplexSolver(1e-4, 10, 1e-6); PointValuePair solution = solver.optimize(new MaxIter(1000), f, new LinearConstraintSet(constraints), GoalType.MINIMIZE, new NonNegativeConstraint(true)); Assert.assertEquals(0.3752298, solution.getValue(), 1e-4); } @Test public void testSimplexSolver() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 7); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2)); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3)); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 4)); SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MAXIMIZE, new NonNegativeConstraint(true)); Assert.assertEquals(2.0, solution.getPoint()[0], 0.0); Assert.assertEquals(2.0, solution.getPoint()[1], 0.0); Assert.assertEquals(57.0, solution.getValue(), 0.0); } @Test public void testSingleVariableAndConstraint() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 3 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 10)); SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MAXIMIZE, new NonNegativeConstraint(false)); Assert.assertEquals(10.0, solution.getPoint()[0], 0.0); Assert.assertEquals(30.0, solution.getValue(), 0.0); } /** * With no artificial variables needed (no equals and no greater than * constraints) we can go straight to Phase 2. */ @Test public void testModelWithNoArtificialVars() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.LEQ, 2)); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.LEQ, 3)); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.LEQ, 4)); SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MAXIMIZE, new NonNegativeConstraint(false)); Assert.assertEquals(2.0, solution.getPoint()[0], 0.0); Assert.assertEquals(2.0, solution.getPoint()[1], 0.0); Assert.assertEquals(50.0, solution.getValue(), 0.0); } @Test public void testMinimization() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, -5); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 6)); constraints.add(new LinearConstraint(new double[] { 3, 2 }, Relationship.LEQ, 12)); constraints.add(new LinearConstraint(new double[] { 0, 1 }, Relationship.GEQ, 0)); SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MINIMIZE, new NonNegativeConstraint(false)); Assert.assertEquals(4.0, solution.getPoint()[0], 0.0); Assert.assertEquals(0.0, solution.getPoint()[1], 0.0); Assert.assertEquals(-13.0, solution.getValue(), 0.0); } @Test public void testSolutionWithNegativeDecisionVariable() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { -2, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.GEQ, 6)); constraints.add(new LinearConstraint(new double[] { 1, 2 }, Relationship.LEQ, 14)); SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MAXIMIZE, new NonNegativeConstraint(false)); Assert.assertEquals(-2.0, solution.getPoint()[0], 0.0); Assert.assertEquals(8.0, solution.getPoint()[1], 0.0); Assert.assertEquals(12.0, solution.getValue(), 0.0); } @Test(expected = NoFeasibleSolutionException.class) public void testInfeasibleSolution() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.LEQ, 1)); constraints.add(new LinearConstraint(new double[] { 1 }, Relationship.GEQ, 3)); SimplexSolver solver = new SimplexSolver(); solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MAXIMIZE, new NonNegativeConstraint(false)); } @Test(expected = UnboundedSolutionException.class) public void testUnboundedSolution() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 15, 10 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 0 }, Relationship.EQ, 2)); SimplexSolver solver = new SimplexSolver(); solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MAXIMIZE, new NonNegativeConstraint(false)); } @Test public void testRestrictVariablesToNonNegative() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 409, 523, 70, 204, 339 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 43, 56, 345, 56, 5 }, Relationship.LEQ, 4567456)); constraints.add(new LinearConstraint(new double[] { 12, 45, 7, 56, 23 }, Relationship.LEQ, 56454)); constraints.add(new LinearConstraint(new double[] { 8, 768, 0, 34, 7456 }, Relationship.LEQ, 1923421)); constraints.add(new LinearConstraint(new double[] { 12342, 2342, 34, 678, 2342 }, Relationship.GEQ, 4356)); constraints.add(new LinearConstraint(new double[] { 45, 678, 76, 52, 23 }, Relationship.EQ, 456356)); SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MAXIMIZE, new NonNegativeConstraint(true)); Assert.assertEquals(2902.92783505155, solution.getPoint()[0], .0000001); Assert.assertEquals(480.419243986254, solution.getPoint()[1], .0000001); Assert.assertEquals(0.0, solution.getPoint()[2], .0000001); Assert.assertEquals(0.0, solution.getPoint()[3], .0000001); Assert.assertEquals(0.0, solution.getPoint()[4], .0000001); Assert.assertEquals(1438556.7491409, solution.getValue(), .0000001); } @Test public void testEpsilon() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 10, 5, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 9, 8, 0 }, Relationship.EQ, 17)); constraints.add(new LinearConstraint(new double[] { 0, 7, 8 }, Relationship.LEQ, 7)); constraints.add(new LinearConstraint(new double[] { 10, 0, 2 }, Relationship.LEQ, 10)); SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MAXIMIZE, new NonNegativeConstraint(false)); Assert.assertEquals(1.0, solution.getPoint()[0], 0.0); Assert.assertEquals(1.0, solution.getPoint()[1], 0.0); Assert.assertEquals(0.0, solution.getPoint()[2], 0.0); Assert.assertEquals(15.0, solution.getValue(), 0.0); } @Test public void testTrivialModel() { LinearObjectiveFunction f = new LinearObjectiveFunction(new double[] { 1, 1 }, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(new LinearConstraint(new double[] { 1, 1 }, Relationship.EQ, 0)); SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MAXIMIZE, new NonNegativeConstraint(true)); Assert.assertEquals(0, solution.getValue(), .0000001); } @Test public void testLargeModel() { double[] objective = new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; LinearObjectiveFunction f = new LinearObjectiveFunction(objective, 0); Collection<LinearConstraint> constraints = new ArrayList<LinearConstraint>(); constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 - x12 = 0")); constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 - x13 = 0")); constraints.add(equationFromString(objective.length, "x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 >= 49")); constraints.add(equationFromString(objective.length, "x0 + x1 + x2 + x3 >= 42")); constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x26 = 0")); constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x27 = 0")); constraints.add(equationFromString(objective.length, "x14 + x15 + x16 + x17 - x12 = 0")); constraints.add(equationFromString(objective.length, "x18 + x19 + x20 + x21 + x22 + x23 + x24 + x25 - x13 = 0")); constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 - x40 = 0")); constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 - x41 = 0")); constraints.add(equationFromString(objective.length, "x32 + x33 + x34 + x35 + x36 + x37 + x38 + x39 >= 49")); constraints.add(equationFromString(objective.length, "x28 + x29 + x30 + x31 >= 42")); constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x54 = 0")); constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x55 = 0")); constraints.add(equationFromString(objective.length, "x42 + x43 + x44 + x45 - x40 = 0")); constraints.add(equationFromString(objective.length, "x46 + x47 + x48 + x49 + x50 + x51 + x52 + x53 - x41 = 0")); constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 - x68 = 0")); constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 - x69 = 0")); constraints.add(equationFromString(objective.length, "x60 + x61 + x62 + x63 + x64 + x65 + x66 + x67 >= 51")); constraints.add(equationFromString(objective.length, "x56 + x57 + x58 + x59 >= 44")); constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x82 = 0")); constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x83 = 0")); constraints.add(equationFromString(objective.length, "x70 + x71 + x72 + x73 - x68 = 0")); constraints.add(equationFromString(objective.length, "x74 + x75 + x76 + x77 + x78 + x79 + x80 + x81 - x69 = 0")); constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 - x96 = 0")); constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 - x97 = 0")); constraints.add(equationFromString(objective.length, "x88 + x89 + x90 + x91 + x92 + x93 + x94 + x95 >= 51")); constraints.add(equationFromString(objective.length, "x84 + x85 + x86 + x87 >= 44")); constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x110 = 0")); constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x111 = 0")); constraints.add(equationFromString(objective.length, "x98 + x99 + x100 + x101 - x96 = 0")); constraints.add(equationFromString(objective.length, "x102 + x103 + x104 + x105 + x106 + x107 + x108 + x109 - x97 = 0")); constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 - x124 = 0")); constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 - x125 = 0")); constraints.add(equationFromString(objective.length, "x116 + x117 + x118 + x119 + x120 + x121 + x122 + x123 >= 49")); constraints.add(equationFromString(objective.length, "x112 + x113 + x114 + x115 >= 42")); constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x138 = 0")); constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x139 = 0")); constraints.add(equationFromString(objective.length, "x126 + x127 + x128 + x129 - x124 = 0")); constraints.add(equationFromString(objective.length, "x130 + x131 + x132 + x133 + x134 + x135 + x136 + x137 - x125 = 0")); constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 - x152 = 0")); constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 - x153 = 0")); constraints.add(equationFromString(objective.length, "x144 + x145 + x146 + x147 + x148 + x149 + x150 + x151 >= 59")); constraints.add(equationFromString(objective.length, "x140 + x141 + x142 + x143 >= 42")); constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x166 = 0")); constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x167 = 0")); constraints.add(equationFromString(objective.length, "x154 + x155 + x156 + x157 - x152 = 0")); constraints.add(equationFromString(objective.length, "x158 + x159 + x160 + x161 + x162 + x163 + x164 + x165 - x153 = 0")); constraints.add(equationFromString(objective.length, "x83 + x82 - x168 = 0")); constraints.add(equationFromString(objective.length, "x111 + x110 - x169 = 0")); constraints.add(equationFromString(objective.length, "x170 - x182 = 0")); constraints.add(equationFromString(objective.length, "x171 - x183 = 0")); constraints.add(equationFromString(objective.length, "x172 - x184 = 0")); constraints.add(equationFromString(objective.length, "x173 - x185 = 0")); constraints.add(equationFromString(objective.length, "x174 - x186 = 0")); constraints.add(equationFromString(objective.length, "x175 + x176 - x187 = 0")); constraints.add(equationFromString(objective.length, "x177 - x188 = 0")); constraints.add(equationFromString(objective.length, "x178 - x189 = 0")); constraints.add(equationFromString(objective.length, "x179 - x190 = 0")); constraints.add(equationFromString(objective.length, "x180 - x191 = 0")); constraints.add(equationFromString(objective.length, "x181 - x192 = 0")); constraints.add(equationFromString(objective.length, "x170 - x26 = 0")); constraints.add(equationFromString(objective.length, "x171 - x27 = 0")); constraints.add(equationFromString(objective.length, "x172 - x54 = 0")); constraints.add(equationFromString(objective.length, "x173 - x55 = 0")); constraints.add(equationFromString(objective.length, "x174 - x168 = 0")); constraints.add(equationFromString(objective.length, "x177 - x169 = 0")); constraints.add(equationFromString(objective.length, "x178 - x138 = 0")); constraints.add(equationFromString(objective.length, "x179 - x139 = 0")); constraints.add(equationFromString(objective.length, "x180 - x166 = 0")); constraints.add(equationFromString(objective.length, "x181 - x167 = 0")); constraints.add(equationFromString(objective.length, "x193 - x205 = 0")); constraints.add(equationFromString(objective.length, "x194 - x206 = 0")); constraints.add(equationFromString(objective.length, "x195 - x207 = 0")); constraints.add(equationFromString(objective.length, "x196 - x208 = 0")); constraints.add(equationFromString(objective.length, "x197 - x209 = 0")); constraints.add(equationFromString(objective.length, "x198 + x199 - x210 = 0")); constraints.add(equationFromString(objective.length, "x200 - x211 = 0")); constraints.add(equationFromString(objective.length, "x201 - x212 = 0")); constraints.add(equationFromString(objective.length, "x202 - x213 = 0")); constraints.add(equationFromString(objective.length, "x203 - x214 = 0")); constraints.add(equationFromString(objective.length, "x204 - x215 = 0")); constraints.add(equationFromString(objective.length, "x193 - x182 = 0")); constraints.add(equationFromString(objective.length, "x194 - x183 = 0")); constraints.add(equationFromString(objective.length, "x195 - x184 = 0")); constraints.add(equationFromString(objective.length, "x196 - x185 = 0")); constraints.add(equationFromString(objective.length, "x197 - x186 = 0")); constraints.add(equationFromString(objective.length, "x198 + x199 - x187 = 0")); constraints.add(equationFromString(objective.length, "x200 - x188 = 0")); constraints.add(equationFromString(objective.length, "x201 - x189 = 0")); constraints.add(equationFromString(objective.length, "x202 - x190 = 0")); constraints.add(equationFromString(objective.length, "x203 - x191 = 0")); constraints.add(equationFromString(objective.length, "x204 - x192 = 0")); SimplexSolver solver = new SimplexSolver(); PointValuePair solution = solver.optimize(DEFAULT_MAX_ITER, f, new LinearConstraintSet(constraints), GoalType.MINIMIZE, new NonNegativeConstraint(true)); Assert.assertEquals(7518.0, solution.getValue(), .0000001); } /** * Converts a test string to a {@link LinearConstraint}. * Ex: x0 + x1 + x2 + x3 - x12 = 0 */ private LinearConstraint equationFromString(int numCoefficients, String s) { Relationship relationship; if (s.contains(">=")) { relationship = Relationship.GEQ; } else if (s.contains("<=")) { relationship = Relationship.LEQ; } else if (s.contains("=")) { relationship = Relationship.EQ; } else { throw new IllegalArgumentException(); } String[] equationParts = s.split("[>|<]?="); double rhs = Double.parseDouble(equationParts[1].trim()); double[] lhs = new double[numCoefficients]; String left = equationParts[0].replaceAll(" ?x", ""); String[] coefficients = left.split(" "); for (String coefficient : coefficients) { double value = coefficient.charAt(0) == '-' ? -1 : 1; int index = Integer.parseInt(coefficient.replaceFirst("[+|-]", "").trim()); lhs[index] = value; } return new LinearConstraint(lhs, relationship, rhs); } private static boolean validSolution(PointValuePair solution, List<LinearConstraint> constraints, double epsilon) { double[] vals = solution.getPoint(); for (LinearConstraint c : constraints) { double[] coeffs = c.getCoefficients().toArray(); double result = 0.0d; for (int i = 0; i < vals.length; i++) { result += vals[i] * coeffs[i]; } switch (c.getRelationship()) { case EQ: if (!Precision.equals(result, c.getValue(), epsilon)) { return false; } break; case GEQ: if (Precision.compareTo(result, c.getValue(), epsilon) < 0) { return false; } break; case LEQ: if (Precision.compareTo(result, c.getValue(), epsilon) > 0) { return false; } break; } } return true; } }
[ { "be_test_class_file": "org/apache/commons/math3/optim/linear/SimplexSolver.java", "be_test_class_name": "org.apache.commons.math3.optim.linear.SimplexSolver", "be_test_function_name": "doIteration", "be_test_function_signature": "(Lorg/apache/commons/math3/optim/linear/SimplexTableau;)V", "line_numbers": [ "226", "228", "229", "230", "231", "235", "236", "239", "240", "241", "242", "245" ], "method_line_rate": 0.9166666666666666 }, { "be_test_class_file": "org/apache/commons/math3/optim/linear/SimplexSolver.java", "be_test_class_name": "org.apache.commons.math3.optim.linear.SimplexSolver", "be_test_function_name": "doOptimize", "be_test_function_signature": "()Ljava/lang/Object;", "line_numbers": [ "56" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/optim/linear/SimplexSolver.java", "be_test_class_name": "org.apache.commons.math3.optim.linear.SimplexSolver", "be_test_function_name": "doOptimize", "be_test_function_signature": "()Lorg/apache/commons/math3/optim/PointValuePair;", "line_numbers": [ "281", "290", "291", "293", "294", "296" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/optim/linear/SimplexSolver.java", "be_test_class_name": "org.apache.commons.math3.optim.linear.SimplexSolver", "be_test_function_name": "getPivotColumn", "be_test_function_signature": "(Lorg/apache/commons/math3/optim/linear/SimplexTableau;)Ljava/lang/Integer;", "line_numbers": [ "124", "125", "126", "127", "130", "131", "132", "135" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/optim/linear/SimplexSolver.java", "be_test_class_name": "org.apache.commons.math3.optim.linear.SimplexSolver", "be_test_function_name": "getPivotRow", "be_test_function_signature": "(Lorg/apache/commons/math3/optim/linear/SimplexTableau;I)Ljava/lang/Integer;", "line_numbers": [ "147", "148", "149", "150", "151", "153", "154", "157", "158", "159", "160", "161", "162", "163", "168", "169", "170", "174", "175", "176", "177", "178", "179", "180", "183", "195", "196", "197", "198", "199", "200", "201", "202", "203", "204", "205", "208", "209", "212" ], "method_line_rate": 0.41025641025641024 }, { "be_test_class_file": "org/apache/commons/math3/optim/linear/SimplexSolver.java", "be_test_class_name": "org.apache.commons.math3.optim.linear.SimplexSolver", "be_test_function_name": "solvePhase1", "be_test_function_signature": "(Lorg/apache/commons/math3/optim/linear/SimplexTableau;)V", "line_numbers": [ "261", "262", "265", "266", "270", "271", "273" ], "method_line_rate": 0.2857142857142857 } ]
public class ZipArchiveInputStreamTest
@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(); } }
// 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 `testWithBytesAfterData` 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-364" * >COMPRESS-364</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;
268
testWithBytesAfterData
```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 `testWithBytesAfterData` 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-364" * >COMPRESS-364</a>. */
249
// 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 `testWithBytesAfterData` 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-364" * >COMPRESS-364</a>. */ @Test public void testWithBytesAfterData() throws Exception {
/** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-364" * >COMPRESS-364</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 `testWithBytesAfterData` 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-364" * >COMPRESS-364</a>. */ @Test public void testWithBytesAfterData() 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;
93ba1fa9a4f1f81b503c40bc0a0e62db14102b6db03d603fd47678f68451737d
[ "org.apache.commons.compress.archivers.zip.ZipArchiveInputStreamTest::testWithBytesAfterData" ]
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 testWithBytesAfterData() 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.8095238095238095 }, { "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": "fill", "be_test_function_signature": "()I", "line_numbers": [ "742", "743", "745", "746", "747", "748", "749", "751" ], "method_line_rate": 0.875 }, { "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": "findEocdRecord", "be_test_function_signature": "()V", "line_numbers": [ "979", "980", "981", "982", "983", "984", "986", "987", "988", "989", "991", "992", "994", "995", "996", "997", "999", "1000", "1002", "1003", "1005", "1007", "1009" ], "method_line_rate": 0.6086956521739131 }, { "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": "getBytesInflated", "be_test_function_signature": "()J", "line_numbers": [ "732", "733", "734", "735", "738" ], "method_line_rate": 0.6 }, { "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.7654320987654321 }, { "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": "isFirstByteOfEocdSig", "be_test_function_signature": "(I)Z", "line_numbers": [ "1050" ], "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": "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": "pushback", "be_test_function_signature": "([BII)V", "line_numbers": [ "937", "938", "939" ], "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": "read", "be_test_function_signature": "([BII)I", "line_numbers": [ "423", "424", "427", "428", "432", "433", "436", "437", "438", "441", "442", "447", "448", "449", "450", "451", "455", "457", "461", "462", "465" ], "method_line_rate": 0.5714285714285714 }, { "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": "readDeflated", "be_test_function_signature": "([BII)I", "line_numbers": [ "511", "512", "513", "514", "515", "516", "519", "520", "523" ], "method_line_rate": 0.5555555555555556 }, { "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": "readFromInflater", "be_test_function_signature": "([BII)I", "line_numbers": [ "531", "533", "534", "535", "536", "537", "538", "544", "545", "546", "547", "548", "549" ], "method_line_rate": 0.6923076923076923 }, { "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 }, { "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": "readOneByte", "be_test_function_signature": "()I", "line_numbers": [ "1042", "1043", "1044", "1046" ], "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": "realSkip", "be_test_function_signature": "(J)V", "line_numbers": [ "1019", "1020", "1021", "1022", "1023", "1024", "1025", "1027", "1028", "1029", "1030", "1032" ], "method_line_rate": 0.8333333333333334 }, { "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": "skip", "be_test_function_signature": "(J)J", "line_numbers": [ "581", "582", "583", "584", "585", "586", "587", "589", "590", "591", "593" ], "method_line_rate": 0.6363636363636364 }, { "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": "skipRemainderOfArchive", "be_test_function_signature": "()V", "line_numbers": [ "966", "967", "968", "969", "971", "972" ], "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": "supportsCompressedSizeFor", "be_test_function_signature": "(Lorg/apache/commons/compress/archivers/zip/ZipArchiveEntry;)Z", "line_numbers": [ "815" ], "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": "supportsDataDescriptorFor", "be_test_function_signature": "(Lorg/apache/commons/compress/archivers/zip/ZipArchiveEntry;)Z", "line_numbers": [ "803" ], "method_line_rate": 1 } ]
public class ExternExportsPassTest extends TestCase
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" ); }
// // 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 `testExportDontEmitPrototypePathPrefix` for the `ExternExportsPass` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** 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. */
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);
401
testExportDontEmitPrototypePathPrefix
```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 `testExportDontEmitPrototypePathPrefix` for the `ExternExportsPass` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** 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. */
380
// // 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 `testExportDontEmitPrototypePathPrefix` for the `ExternExportsPass` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** 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() {
/** 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. */
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 `testExportDontEmitPrototypePathPrefix` for the `ExternExportsPass` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** 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() { ```
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);
977ca7d0d687ad1ab5c801e56266c863076ab04fd72b3ba27a266bd4a1335f58
[ "com.google.javascript.jscomp.ExternExportsPassTest::testExportDontEmitPrototypePathPrefix" ]
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 testExportDontEmitPrototypePathPrefix()
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": "handlePropertyExport", "be_test_function_signature": "(Lcom/google/javascript/rhino/Node;)V", "line_numbers": [ "475", "476", "479", "480", "481", "482", "486", "487", "490", "491", "495", "499" ], "method_line_rate": 0.75 }, { "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": 1 } ]
public class JsFunctionParserTest extends TestCase
public void testParseFile() { final String CONTENTS = "/*" + "goog.provide('no1');*//*\n" + "goog.provide('no2');\n" + "*/goog.provide('yes1');\n" + "/* blah */goog.provide(\"yes2\")/* blah*/\n" + "goog.require('yes3'); // goog.provide('no3');\n" + "// goog.provide('no4');\n" + "goog.require(\"" + "bar.data.SuperstarAddStarThreadActionRequestDelegate\"); " + "//no new line at EOF"; Collection<SymbolInfo> symbols = parser.parseFile(SRC_PATH, CONTENTS); Iterator<SymbolInfo> i = symbols.iterator(); SymbolInfo symbolInfo = i.next(); assertEquals(symbolInfo.symbol, "yes1"); assertEquals(symbolInfo.functionName, "goog.provide"); symbolInfo = i.next(); assertEquals(symbolInfo.symbol, "yes2"); assertEquals(symbolInfo.functionName, "goog.provide"); symbolInfo = i.next(); assertEquals(symbolInfo.symbol, "yes3"); assertEquals(symbolInfo.functionName, "goog.require"); symbolInfo = i.next(); assertEquals(symbolInfo.symbol, "bar.data.SuperstarAddStarThreadActionRequestDelegate"); assertEquals(symbolInfo.functionName, "goog.require"); assertEquals(symbols.size(), 4); assertEquals(0, errorManager.getErrorCount()); assertEquals(0, errorManager.getWarningCount()); }
// // Abstract Java Tested Class // package com.google.javascript.jscomp.deps; // // import com.google.common.base.CharMatcher; // import com.google.common.collect.Lists; // import com.google.javascript.jscomp.ErrorManager; // import java.io.Reader; // import java.io.StringReader; // import java.util.Collection; // import java.util.logging.Logger; // import java.util.regex.Matcher; // import java.util.regex.Pattern; // // // // public class JsFunctionParser extends JsFileLineParser { // private static Logger logger = // Logger.getLogger(JsFunctionParser.class.getName()); // private Pattern pattern; // private Matcher matcher; // private Collection<SymbolInfo> symbols; // private Collection<String> functionsToParse; // // public JsFunctionParser( // Collection<String> functions, ErrorManager errorManager); // private Pattern getPattern(Collection<String> functions); // public Collection<SymbolInfo> parseFile( // String filePath, String fileContents); // private Collection<SymbolInfo> parseReader( // String filePath, Reader fileContents); // @Override // protected boolean parseLine(String line) throws ParseException; // private SymbolInfo(String functionName, String symbol); // } // // // Abstract Java Test Class // package com.google.javascript.jscomp.deps; // // import com.google.common.collect.Lists; // import com.google.javascript.jscomp.ErrorManager; // import com.google.javascript.jscomp.PrintStreamErrorManager; // import com.google.javascript.jscomp.deps.JsFunctionParser.SymbolInfo; // import junit.framework.TestCase; // import java.util.Collection; // import java.util.Iterator; // // // // public class JsFunctionParserTest extends TestCase { // private static final String SRC_PATH = "a"; // private JsFunctionParser parser; // private ErrorManager errorManager; // private Collection<String> functions = Lists.newArrayList( // "goog.require", "goog.provide"); // // @Override // public void setUp(); // public void testParseFile(); // public void testMultiplePerLine(); // public void testShortcutMode1(); // public void testShortcutMode2(); // public void testShortcutMode3(); // } // You are a professional Java test case writer, please create a test case named `testParseFile` for the `JsFunctionParser` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests: * -Parsing of comments, * -Parsing of different styles of quotes, * -Correct recording of what was parsed. */
test/com/google/javascript/jscomp/deps/JsFunctionParserTest.java
package com.google.javascript.jscomp.deps; import com.google.common.base.CharMatcher; import com.google.common.collect.Lists; import com.google.javascript.jscomp.ErrorManager; import java.io.Reader; import java.io.StringReader; import java.util.Collection; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern;
public JsFunctionParser( Collection<String> functions, ErrorManager errorManager); private Pattern getPattern(Collection<String> functions); public Collection<SymbolInfo> parseFile( String filePath, String fileContents); private Collection<SymbolInfo> parseReader( String filePath, Reader fileContents); @Override protected boolean parseLine(String line) throws ParseException; private SymbolInfo(String functionName, String symbol);
89
testParseFile
```java // Abstract Java Tested Class package com.google.javascript.jscomp.deps; import com.google.common.base.CharMatcher; import com.google.common.collect.Lists; import com.google.javascript.jscomp.ErrorManager; import java.io.Reader; import java.io.StringReader; import java.util.Collection; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; public class JsFunctionParser extends JsFileLineParser { private static Logger logger = Logger.getLogger(JsFunctionParser.class.getName()); private Pattern pattern; private Matcher matcher; private Collection<SymbolInfo> symbols; private Collection<String> functionsToParse; public JsFunctionParser( Collection<String> functions, ErrorManager errorManager); private Pattern getPattern(Collection<String> functions); public Collection<SymbolInfo> parseFile( String filePath, String fileContents); private Collection<SymbolInfo> parseReader( String filePath, Reader fileContents); @Override protected boolean parseLine(String line) throws ParseException; private SymbolInfo(String functionName, String symbol); } // Abstract Java Test Class package com.google.javascript.jscomp.deps; import com.google.common.collect.Lists; import com.google.javascript.jscomp.ErrorManager; import com.google.javascript.jscomp.PrintStreamErrorManager; import com.google.javascript.jscomp.deps.JsFunctionParser.SymbolInfo; import junit.framework.TestCase; import java.util.Collection; import java.util.Iterator; public class JsFunctionParserTest extends TestCase { private static final String SRC_PATH = "a"; private JsFunctionParser parser; private ErrorManager errorManager; private Collection<String> functions = Lists.newArrayList( "goog.require", "goog.provide"); @Override public void setUp(); public void testParseFile(); public void testMultiplePerLine(); public void testShortcutMode1(); public void testShortcutMode2(); public void testShortcutMode3(); } ``` You are a professional Java test case writer, please create a test case named `testParseFile` for the `JsFunctionParser` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests: * -Parsing of comments, * -Parsing of different styles of quotes, * -Correct recording of what was parsed. */
54
// // Abstract Java Tested Class // package com.google.javascript.jscomp.deps; // // import com.google.common.base.CharMatcher; // import com.google.common.collect.Lists; // import com.google.javascript.jscomp.ErrorManager; // import java.io.Reader; // import java.io.StringReader; // import java.util.Collection; // import java.util.logging.Logger; // import java.util.regex.Matcher; // import java.util.regex.Pattern; // // // // public class JsFunctionParser extends JsFileLineParser { // private static Logger logger = // Logger.getLogger(JsFunctionParser.class.getName()); // private Pattern pattern; // private Matcher matcher; // private Collection<SymbolInfo> symbols; // private Collection<String> functionsToParse; // // public JsFunctionParser( // Collection<String> functions, ErrorManager errorManager); // private Pattern getPattern(Collection<String> functions); // public Collection<SymbolInfo> parseFile( // String filePath, String fileContents); // private Collection<SymbolInfo> parseReader( // String filePath, Reader fileContents); // @Override // protected boolean parseLine(String line) throws ParseException; // private SymbolInfo(String functionName, String symbol); // } // // // Abstract Java Test Class // package com.google.javascript.jscomp.deps; // // import com.google.common.collect.Lists; // import com.google.javascript.jscomp.ErrorManager; // import com.google.javascript.jscomp.PrintStreamErrorManager; // import com.google.javascript.jscomp.deps.JsFunctionParser.SymbolInfo; // import junit.framework.TestCase; // import java.util.Collection; // import java.util.Iterator; // // // // public class JsFunctionParserTest extends TestCase { // private static final String SRC_PATH = "a"; // private JsFunctionParser parser; // private ErrorManager errorManager; // private Collection<String> functions = Lists.newArrayList( // "goog.require", "goog.provide"); // // @Override // public void setUp(); // public void testParseFile(); // public void testMultiplePerLine(); // public void testShortcutMode1(); // public void testShortcutMode2(); // public void testShortcutMode3(); // } // You are a professional Java test case writer, please create a test case named `testParseFile` for the `JsFunctionParser` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests: * -Parsing of comments, * -Parsing of different styles of quotes, * -Correct recording of what was parsed. */ public void testParseFile() {
/** * Tests: * -Parsing of comments, * -Parsing of different styles of quotes, * -Correct recording of what was parsed. */
107
com.google.javascript.jscomp.deps.JsFunctionParser
test
```java // Abstract Java Tested Class package com.google.javascript.jscomp.deps; import com.google.common.base.CharMatcher; import com.google.common.collect.Lists; import com.google.javascript.jscomp.ErrorManager; import java.io.Reader; import java.io.StringReader; import java.util.Collection; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; public class JsFunctionParser extends JsFileLineParser { private static Logger logger = Logger.getLogger(JsFunctionParser.class.getName()); private Pattern pattern; private Matcher matcher; private Collection<SymbolInfo> symbols; private Collection<String> functionsToParse; public JsFunctionParser( Collection<String> functions, ErrorManager errorManager); private Pattern getPattern(Collection<String> functions); public Collection<SymbolInfo> parseFile( String filePath, String fileContents); private Collection<SymbolInfo> parseReader( String filePath, Reader fileContents); @Override protected boolean parseLine(String line) throws ParseException; private SymbolInfo(String functionName, String symbol); } // Abstract Java Test Class package com.google.javascript.jscomp.deps; import com.google.common.collect.Lists; import com.google.javascript.jscomp.ErrorManager; import com.google.javascript.jscomp.PrintStreamErrorManager; import com.google.javascript.jscomp.deps.JsFunctionParser.SymbolInfo; import junit.framework.TestCase; import java.util.Collection; import java.util.Iterator; public class JsFunctionParserTest extends TestCase { private static final String SRC_PATH = "a"; private JsFunctionParser parser; private ErrorManager errorManager; private Collection<String> functions = Lists.newArrayList( "goog.require", "goog.provide"); @Override public void setUp(); public void testParseFile(); public void testMultiplePerLine(); public void testShortcutMode1(); public void testShortcutMode2(); public void testShortcutMode3(); } ``` You are a professional Java test case writer, please create a test case named `testParseFile` for the `JsFunctionParser` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests: * -Parsing of comments, * -Parsing of different styles of quotes, * -Correct recording of what was parsed. */ public void testParseFile() { ```
public class JsFunctionParser extends JsFileLineParser
package com.google.javascript.jscomp.deps; import com.google.common.collect.Lists; import com.google.javascript.jscomp.ErrorManager; import com.google.javascript.jscomp.PrintStreamErrorManager; import com.google.javascript.jscomp.deps.JsFunctionParser.SymbolInfo; import junit.framework.TestCase; import java.util.Collection; import java.util.Iterator;
@Override public void setUp(); public void testParseFile(); public void testMultiplePerLine(); public void testShortcutMode1(); public void testShortcutMode2(); public void testShortcutMode3();
99d67dcd9dc6ba33d143b73442aba6ea02f52d25ed6c1ee91d51d1b6f4117a87
[ "com.google.javascript.jscomp.deps.JsFunctionParserTest::testParseFile" ]
private static Logger logger = Logger.getLogger(JsFunctionParser.class.getName()); private Pattern pattern; private Matcher matcher; private Collection<SymbolInfo> symbols; private Collection<String> functionsToParse;
public void testParseFile()
private static final String SRC_PATH = "a"; private JsFunctionParser parser; private ErrorManager errorManager; private Collection<String> functions = Lists.newArrayList( "goog.require", "goog.provide");
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.deps; import com.google.common.collect.Lists; import com.google.javascript.jscomp.ErrorManager; import com.google.javascript.jscomp.PrintStreamErrorManager; import com.google.javascript.jscomp.deps.JsFunctionParser.SymbolInfo; import junit.framework.TestCase; import java.util.Collection; import java.util.Iterator; /** * Tests for {@link JsFunctionParser} * * @author agrieve@google.com (Andrew Grieve) * @author ielashi@google.com (Islam El-Ashi) */ public class JsFunctionParserTest extends TestCase { private static final String SRC_PATH = "a"; private JsFunctionParser parser; private ErrorManager errorManager; private Collection<String> functions = Lists.newArrayList( "goog.require", "goog.provide"); @Override public void setUp() { errorManager = new PrintStreamErrorManager(System.err); parser = new JsFunctionParser(functions, errorManager); parser.setShortcutMode(true); } /** * Tests: * -Parsing of comments, * -Parsing of different styles of quotes, * -Correct recording of what was parsed. */ public void testParseFile() { final String CONTENTS = "/*" + "goog.provide('no1');*//*\n" + "goog.provide('no2');\n" + "*/goog.provide('yes1');\n" + "/* blah */goog.provide(\"yes2\")/* blah*/\n" + "goog.require('yes3'); // goog.provide('no3');\n" + "// goog.provide('no4');\n" + "goog.require(\"" + "bar.data.SuperstarAddStarThreadActionRequestDelegate\"); " + "//no new line at EOF"; Collection<SymbolInfo> symbols = parser.parseFile(SRC_PATH, CONTENTS); Iterator<SymbolInfo> i = symbols.iterator(); SymbolInfo symbolInfo = i.next(); assertEquals(symbolInfo.symbol, "yes1"); assertEquals(symbolInfo.functionName, "goog.provide"); symbolInfo = i.next(); assertEquals(symbolInfo.symbol, "yes2"); assertEquals(symbolInfo.functionName, "goog.provide"); symbolInfo = i.next(); assertEquals(symbolInfo.symbol, "yes3"); assertEquals(symbolInfo.functionName, "goog.require"); symbolInfo = i.next(); assertEquals(symbolInfo.symbol, "bar.data.SuperstarAddStarThreadActionRequestDelegate"); assertEquals(symbolInfo.functionName, "goog.require"); assertEquals(symbols.size(), 4); assertEquals(0, errorManager.getErrorCount()); assertEquals(0, errorManager.getWarningCount()); } public void testMultiplePerLine() { final String CONTENTS = "goog.provide('yes1');goog.provide('yes2');/*" + "goog.provide('no1');*/goog.provide('yes3');//goog.provide('no2');"; Collection<SymbolInfo> symbols = parser.parseFile(SRC_PATH, CONTENTS); Iterator<SymbolInfo> i = symbols.iterator(); SymbolInfo symbolInfo = i.next(); assertEquals(symbolInfo.symbol, "yes1"); assertEquals(symbolInfo.functionName, "goog.provide"); symbolInfo = i.next(); assertEquals(symbolInfo.symbol, "yes2"); assertEquals(symbolInfo.functionName, "goog.provide"); symbolInfo = i.next(); assertEquals(symbolInfo.symbol, "yes3"); assertEquals(symbolInfo.functionName, "goog.provide"); assertEquals(symbols.size(), 3); assertEquals(0, errorManager.getErrorCount()); assertEquals(0, errorManager.getWarningCount()); } public void testShortcutMode1() { // For efficiency reasons, we stop reading after the ctor. final String CONTENTS = " // hi ! \n /* this is a comment */ " + "goog.provide('yes1');\n /* and another comment */ \n" + "goog.provide('yes2'); // include this\n" + "function foo() {}\n" + "goog.provide('no1');"; Collection<SymbolInfo> symbols = parser.parseFile(SRC_PATH, CONTENTS); Iterator<SymbolInfo> i = symbols.iterator(); SymbolInfo symbolInfo = i.next(); assertEquals(symbolInfo.symbol, "yes1"); assertEquals(symbolInfo.functionName, "goog.provide"); symbolInfo = i.next(); assertEquals(symbolInfo.symbol, "yes2"); assertEquals(symbolInfo.functionName, "goog.provide"); assertEquals(symbols.size(), 2); assertEquals(0, errorManager.getErrorCount()); assertEquals(0, errorManager.getWarningCount()); } public void testShortcutMode2() { final String CONTENTS = "/** goog.provide('no1'); \n" + " * goog.provide('no2');\n */\n" + "goog.provide('yes1');\n"; Collection<SymbolInfo> symbols = parser.parseFile(SRC_PATH, CONTENTS); Iterator<SymbolInfo> i = symbols.iterator(); SymbolInfo symbolInfo = i.next(); assertEquals(symbolInfo.symbol, "yes1"); assertEquals(symbolInfo.functionName, "goog.provide"); assertEquals(symbols.size(), 1); assertEquals(0, errorManager.getErrorCount()); assertEquals(0, errorManager.getWarningCount()); } public void testShortcutMode3() { final String CONTENTS = "/**\n" + " * goog.provide('no1');\n */\n" + "goog.provide('yes1');\n"; Collection<SymbolInfo> symbols = parser.parseFile(SRC_PATH, CONTENTS); Iterator<SymbolInfo> i = symbols.iterator(); SymbolInfo symbolInfo = i.next(); assertEquals(symbolInfo.symbol, "yes1"); assertEquals(symbolInfo.functionName, "goog.provide"); assertEquals(0, errorManager.getErrorCount()); assertEquals(0, errorManager.getWarningCount()); } }
[ { "be_test_class_file": "com/google/javascript/jscomp/deps/JsFunctionParser.java", "be_test_class_name": "com.google.javascript.jscomp.deps.JsFunctionParser", "be_test_function_name": "getPattern", "be_test_function_signature": "(Ljava/util/Collection;)Ljava/util/regex/Pattern;", "line_numbers": [ "84", "86", "87", "88", "91", "92", "94" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/deps/JsFunctionParser.java", "be_test_class_name": "com.google.javascript.jscomp.deps.JsFunctionParser", "be_test_function_name": "parseFile", "be_test_function_signature": "(Ljava/lang/String;Ljava/lang/String;)Ljava/util/Collection;", "line_numbers": [ "108" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/deps/JsFunctionParser.java", "be_test_class_name": "com.google.javascript.jscomp.deps.JsFunctionParser", "be_test_function_name": "parseLine", "be_test_function_signature": "(Ljava/lang/String;)Z", "line_numbers": [ "126", "127", "131", "132", "133", "134", "136", "138", "139", "140", "141", "142", "143", "144", "145", "148" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/jscomp/deps/JsFunctionParser.java", "be_test_class_name": "com.google.javascript.jscomp.deps.JsFunctionParser", "be_test_function_name": "parseReader", "be_test_function_signature": "(Ljava/lang/String;Ljava/io/Reader;)Ljava/util/Collection;", "line_numbers": [ "113", "115", "116", "118" ], "method_line_rate": 1 } ]
public class LoopingIteratorTest extends TestCase
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()); }
// // 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 `testLooping3` for the `LoopingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests whether a populated looping iterator works as designed. * @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();
117
testLooping3
```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 `testLooping3` for the `LoopingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests whether a populated looping iterator works as designed. * @throws Exception If something unexpected occurs. */
101
// // 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 `testLooping3` for the `LoopingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests whether a populated looping iterator works as designed. * @throws Exception If something unexpected occurs. */ public void testLooping3() throws Exception {
/** * Tests whether a populated looping iterator works as designed. * @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 `testLooping3` for the `LoopingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests whether a populated looping iterator works as designed. * @throws Exception If something unexpected occurs. */ public void testLooping3() 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;
9bfabda7b9ab559a6b146bd0bfde4724362c5854b60db0dd8e0ec87e84793f73
[ "org.apache.commons.collections4.iterators.LoopingIteratorTest::testLooping3" ]
private final Collection<? extends E> collection; private Iterator<? extends E> iterator;
public void testLooping3() 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": "hasNext", "be_test_function_signature": "()Z", "line_numbers": [ "72" ], "method_line_rate": 1 }, { "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.8 }, { "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 } ]
public class XYPlotTests extends TestCase
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); }
// 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 `testSerialization3` for the `XYPlot` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * 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). */
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();
809
testSerialization3
```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 `testSerialization3` for the `XYPlot` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * 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). */
775
// 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 `testSerialization3` for the `XYPlot` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * 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() {
/** * 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). */
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 `testSerialization3` for the `XYPlot` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * 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() { ```
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();
9cb0c26f4385d15232f549a6cdba139f0cb0772e2cc26ea829f6522440e32209
[ "org.jfree.chart.plot.junit.XYPlotTests::testSerialization3" ]
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 testSerialization3()
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": "calculateAxisSpace", "be_test_function_signature": "(Ljava/awt/Graphics2D;Ljava/awt/geom/Rectangle2D;)Lorg/jfree/chart/axis/AxisSpace;", "line_numbers": [ "3094", "3095", "3096", "3097", "3098" ], "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": "calculateDomainAxisSpace", "be_test_function_signature": "(Ljava/awt/Graphics2D;Ljava/awt/geom/Rectangle2D;Lorg/jfree/chart/axis/AxisSpace;)Lorg/jfree/chart/axis/AxisSpace;", "line_numbers": [ "3114", "3115", "3119", "3120", "3121", "3123", "3126", "3127", "3129", "3135", "3136", "3137", "3138", "3139", "3144" ], "method_line_rate": 0.5333333333333333 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "calculateRangeAxisSpace", "be_test_function_signature": "(Ljava/awt/Graphics2D;Ljava/awt/geom/Rectangle2D;Lorg/jfree/chart/axis/AxisSpace;)Lorg/jfree/chart/axis/AxisSpace;", "line_numbers": [ "3161", "3162", "3166", "3167", "3168", "3170", "3173", "3174", "3176", "3182", "3183", "3184", "3185", "3186", "3190" ], "method_line_rate": 0.5333333333333333 }, { "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": "draw", "be_test_function_signature": "(Ljava/awt/Graphics2D;Ljava/awt/geom/Rectangle2D;Ljava/awt/geom/Point2D;Lorg/jfree/chart/plot/PlotState;Lorg/jfree/chart/plot/PlotRenderingInfo;)V", "line_numbers": [ "3225", "3226", "3227", "3228", "3232", "3233", "3237", "3238", "3240", "3241", "3242", "3244", "3245", "3246", "3248", "3249", "3250", "3254", "3255", "3257", "3261", "3262", "3264", "3265", "3266", "3268", "3269", "3270", "3271", "3272", "3274", "3275", "3279", "3282", "3284", "3285", "3287", "3288", "3292", "3295", "3298", "3299", "3300", "3301", "3303", "3304", "3307", "3309", "3310", "3311", "3316", "3317", "3318", "3319", "3323", "3324", "3326", "3327", "3329", "3330", "3331", "3333", "3334", "3335", "3338", "3339", "3340", "3341", "3342", "3344", "3345", "3346", "3351", "3352", "3354", "3355", "3359", "3360", "3361", "3364", "3365", "3366", "3367", "3368", "3369", "3370", "3376", "3377", "3382", "3383", "3384", "3385", "3386", "3387", "3392", "3393", "3396", "3397", "3398", "3399", "3400", "3402", "3403", "3404", "3405", "3410", "3411", "3416", "3417", "3418", "3419", "3421", "3422", "3423", "3424", "3432", "3433", "3434", "3435", "3437", "3438", "3441", "3443", "3445", "3446", "3447", "3448", "3449", "3450", "3454", "3455", "3456", "3457", "3459", "3460", "3462", "3464", "3466", "3467", "3468", "3469", "3470", "3471", "3474", "3475", "3478", "3479", "3481", "3482", "3485", "3486", "3487", "3489", "3490", "3491", "3495", "3498", "3499", "3501", "3503" ], "method_line_rate": 0.6 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "drawAnnotations", "be_test_function_signature": "(Ljava/awt/Graphics2D;Ljava/awt/geom/Rectangle2D;Lorg/jfree/chart/plot/PlotRenderingInfo;)V", "line_numbers": [ "4099", "4100", "4101", "4102", "4103", "4104", "4105", "4107" ], "method_line_rate": 0.375 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "drawAxes", "be_test_function_signature": "(Ljava/awt/Graphics2D;Ljava/awt/geom/Rectangle2D;Ljava/awt/geom/Rectangle2D;Lorg/jfree/chart/plot/PlotRenderingInfo;)Ljava/util/Map;", "line_numbers": [ "3719", "3722", "3723", "3724", "3725", "3730", "3731", "3732", "3733", "3737", "3740", "3742", "3743", "3744", "3745", "3747", "3748", "3749", "3752", "3754", "3755", "3756", "3757", "3759", "3760", "3761", "3764", "3766", "3767", "3768", "3769", "3771", "3772", "3773", "3776", "3778", "3779", "3780", "3781", "3783", "3784", "3785", "3787" ], "method_line_rate": 0.7674418604651163 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "drawBackground", "be_test_function_signature": "(Ljava/awt/Graphics2D;Ljava/awt/geom/Rectangle2D;)V", "line_numbers": [ "3512", "3513", "3514", "3515" ], "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": "drawDomainGridlines", "be_test_function_signature": "(Ljava/awt/Graphics2D;Ljava/awt/geom/Rectangle2D;Ljava/util/List;)V", "line_numbers": [ "3968", "3969", "3973", "3974", "3975", "3976", "3977", "3978", "3979", "3980", "3981", "3983", "3984", "3985", "3987", "3989", "3990", "3991", "3993", "3994", "3995", "3999", "4001" ], "method_line_rate": 0.8260869565217391 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "drawDomainMarkers", "be_test_function_signature": "(Ljava/awt/Graphics2D;Ljava/awt/geom/Rectangle2D;ILorg/jfree/chart/util/Layer;)V", "line_numbers": [ "4121", "4122", "4123", "4127", "4128", "4130", "4131", "4132", "4133", "4134", "4135", "4136", "4137", "4140" ], "method_line_rate": 0.5 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "drawDomainTickBands", "be_test_function_signature": "(Ljava/awt/Graphics2D;Ljava/awt/geom/Rectangle2D;Ljava/util/List;)V", "line_numbers": [ "3644", "3645", "3646", "3647", "3648", "3649", "3650", "3651", "3652", "3653", "3654", "3657", "3658", "3659", "3660", "3661", "3662", "3666" ], "method_line_rate": 0.16666666666666666 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "drawQuadrants", "be_test_function_signature": "(Ljava/awt/Graphics2D;Ljava/awt/geom/Rectangle2D;)V", "line_numbers": [ "3530", "3532", "3533", "3534", "3536", "3537", "3539", "3540", "3541", "3543", "3544", "3546", "3547", "3549", "3550", "3552", "3553", "3555", "3556", "3558", "3559", "3560", "3561", "3562", "3567", "3571", "3574", "3575", "3576", "3577", "3582", "3586", "3589", "3590", "3591", "3592", "3597", "3601", "3604", "3605", "3606", "3607", "3612", "3616", "3619", "3620", "3621", "3623", "3624", "3625", "3626", "3629", "3631" ], "method_line_rate": 0.4528301886792453 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "drawRangeGridlines", "be_test_function_signature": "(Ljava/awt/Graphics2D;Ljava/awt/geom/Rectangle2D;Ljava/util/List;)V", "line_numbers": [ "4017", "4018", "4022", "4023", "4024", "4025", "4026", "4027", "4028", "4029", "4030", "4031", "4032", "4034", "4035", "4036", "4038", "4040", "4041", "4042", "4044", "4046", "4049", "4052" ], "method_line_rate": 0.8333333333333334 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "drawRangeMarkers", "be_test_function_signature": "(Ljava/awt/Graphics2D;Ljava/awt/geom/Rectangle2D;ILorg/jfree/chart/util/Layer;)V", "line_numbers": [ "4154", "4155", "4156", "4160", "4161", "4163", "4164", "4165", "4166", "4167", "4168", "4169", "4170", "4172" ], "method_line_rate": 0.5 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "drawRangeTickBands", "be_test_function_signature": "(Ljava/awt/Graphics2D;Ljava/awt/geom/Rectangle2D;Ljava/util/List;)V", "line_numbers": [ "3679", "3680", "3681", "3682", "3683", "3684", "3685", "3686", "3687", "3688", "3689", "3692", "3693", "3694", "3695", "3696", "3697", "3701" ], "method_line_rate": 0.16666666666666666 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "drawZeroDomainBaseline", "be_test_function_signature": "(Ljava/awt/Graphics2D;Ljava/awt/geom/Rectangle2D;)V", "line_numbers": [ "4065", "4066", "4067", "4071" ], "method_line_rate": 0.5 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "drawZeroRangeBaseline", "be_test_function_signature": "(Ljava/awt/Graphics2D;Ljava/awt/geom/Rectangle2D;)V", "line_numbers": [ "4082", "4083", "4086" ], "method_line_rate": 0.6666666666666666 }, { "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.5132743362831859 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "getAnnotations", "be_test_function_signature": "()Ljava/util/List;", "line_numbers": [ "3039" ], "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": "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": "getDatasetRenderingOrder", "be_test_function_signature": "()Lorg/jfree/chart/plot/DatasetRenderingOrder;", "line_numbers": [ "1695" ], "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.7272727272727273 }, { "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.7272727272727273 }, { "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": "()Lorg/jfree/chart/axis/ValueAxis;", "line_numbers": [ "805" ], "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": "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.5555555555555556 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "getDomainAxisCount", "be_test_function_signature": "()I", "line_numbers": [ "962" ], "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": "getDomainAxisEdge", "be_test_function_signature": "()Lorg/jfree/chart/util/RectangleEdge;", "line_numbers": [ "950" ], "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": "getDomainAxisEdge", "be_test_function_signature": "(I)Lorg/jfree/chart/util/RectangleEdge;", "line_numbers": [ "1068", "1069", "1071", "1072", "1074" ], "method_line_rate": 0.8 }, { "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.8181818181818182 }, { "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": "getDomainAxisLocation", "be_test_function_signature": "()Lorg/jfree/chart/axis/AxisLocation;", "line_numbers": [ "910" ], "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": "getDomainAxisLocation", "be_test_function_signature": "(I)Lorg/jfree/chart/axis/AxisLocation;", "line_numbers": [ "1006", "1007", "1008", "1010", "1011", "1013" ], "method_line_rate": 0.8333333333333334 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "getDomainCrosshairValue", "be_test_function_signature": "()D", "line_numbers": [ "4739" ], "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": "getDomainGridlinePaint", "be_test_function_signature": "()Ljava/awt/Paint;", "line_numbers": [ "1945" ], "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": "getDomainGridlineStroke", "be_test_function_signature": "()Ljava/awt/Stroke;", "line_numbers": [ "1878" ], "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": "getDomainMarkers", "be_test_function_signature": "(ILorg/jfree/chart/util/Layer;)Ljava/util/Collection;", "line_numbers": [ "4212", "4213", "4214", "4215", "4217", "4218", "4220", "4221", "4223" ], "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": "getDomainTickBandPaint", "be_test_function_signature": "()Ljava/awt/Paint;", "line_numbers": [ "2369" ], "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": "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": "getLegendItems", "be_test_function_signature": "()Lorg/jfree/chart/LegendItemCollection;", "line_numbers": [ "5392", "5393", "5395", "5396", "5397", "5398", "5399", "5400", "5401", "5402", "5404", "5405", "5406", "5407", "5409", "5411", "5412", "5419" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "getOrientation", "be_test_function_signature": "()Lorg/jfree/chart/plot/PlotOrientation;", "line_numbers": [ "746" ], "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": "()Lorg/jfree/chart/axis/ValueAxis;", "line_numbers": [ "1088" ], "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.5555555555555556 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "getRangeAxisCount", "be_test_function_signature": "()I", "line_numbers": [ "1260" ], "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": "getRangeAxisEdge", "be_test_function_signature": "()Lorg/jfree/chart/util/RectangleEdge;", "line_numbers": [ "1168" ], "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": "getRangeAxisEdge", "be_test_function_signature": "(I)Lorg/jfree/chart/util/RectangleEdge;", "line_numbers": [ "1368", "1369", "1371", "1372", "1374" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "getRangeAxisForDataset", "be_test_function_signature": "(I)Lorg/jfree/chart/axis/ValueAxis;", "line_numbers": [ "3936", "3937", "3938", "3941", "3942", "3944", "3946", "3947", "3948", "3950", "3952" ], "method_line_rate": 0.8181818181818182 }, { "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": "getRangeAxisLocation", "be_test_function_signature": "()Lorg/jfree/chart/axis/AxisLocation;", "line_numbers": [ "1129" ], "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": "getRangeAxisLocation", "be_test_function_signature": "(I)Lorg/jfree/chart/axis/AxisLocation;", "line_numbers": [ "1306", "1307", "1308", "1310", "1311", "1313" ], "method_line_rate": 0.8333333333333334 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "getRangeCrosshairValue", "be_test_function_signature": "()D", "line_numbers": [ "4894" ], "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": "getRangeGridlinePaint", "be_test_function_signature": "()Ljava/awt/Paint;", "line_numbers": [ "2069" ], "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": "getRangeGridlineStroke", "be_test_function_signature": "()Ljava/awt/Stroke;", "line_numbers": [ "2041" ], "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": "getRangeMarkers", "be_test_function_signature": "(ILorg/jfree/chart/util/Layer;)Ljava/util/Collection;", "line_numbers": [ "4238", "4239", "4240", "4241", "4243", "4244", "4246", "4247", "4249" ], "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": "getRangeTickBandPaint", "be_test_function_signature": "()Ljava/awt/Paint;", "line_numbers": [ "2393" ], "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": "()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": 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": "integerise", "be_test_function_signature": "(Ljava/awt/geom/Rectangle2D;)Ljava/awt/Rectangle;", "line_numbers": [ "3202", "3203", "3204", "3205", "3206" ], "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": "isDomainCrosshairVisible", "be_test_function_signature": "()Z", "line_numbers": [ "4684" ], "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": "isDomainGridlinesVisible", "be_test_function_signature": "()Z", "line_numbers": [ "1814" ], "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": "isDomainMinorGridlinesVisible", "be_test_function_signature": "()Z", "line_numbers": [ "1846" ], "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": "isDomainZeroBaselineVisible", "be_test_function_signature": "()Z", "line_numbers": [ "2197" ], "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": "isRangeCrosshairVisible", "be_test_function_signature": "()Z", "line_numbers": [ "4839" ], "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": "isRangeGridlinesVisible", "be_test_function_signature": "()Z", "line_numbers": [ "2011" ], "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": "isRangeMinorGridlinesVisible", "be_test_function_signature": "()Z", "line_numbers": [ "2099" ], "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": "isRangeZeroBaselineVisible", "be_test_function_signature": "()Z", "line_numbers": [ "2288" ], "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": "render", "be_test_function_signature": "(Ljava/awt/Graphics2D;Ljava/awt/geom/Rectangle2D;ILorg/jfree/chart/plot/PlotRenderingInfo;Lorg/jfree/chart/plot/CrosshairState;)Z", "line_numbers": [ "3809", "3810", "3811", "3812", "3813", "3814", "3815", "3816", "3818", "3819", "3820", "3821", "3822", "3826", "3828", "3829", "3831", "3832", "3834", "3835", "3836", "3837", "3838", "3839", "3840", "3842", "3843", "3846", "3847", "3849", "3851", "3852", "3853", "3854", "3857", "3861", "3868", "3869", "3870", "3871", "3872", "3873", "3874", "3877", "3878", "3880", "3882", "3883", "3884", "3885", "3888", "3892", "3898" ], "method_line_rate": 0.07547169811320754 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "rendererChanged", "be_test_function_signature": "(Lorg/jfree/chart/event/RendererChangeEvent;)V", "line_numbers": [ "4669", "4670", "4671", "4673", "4674" ], "method_line_rate": 0.6 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "setAxisOffset", "be_test_function_signature": "(Lorg/jfree/chart/util/RectangleInsets;)V", "line_numbers": [ "787", "788", "790", "791", "792" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "setDomainCrosshairPaint", "be_test_function_signature": "(Ljava/awt/Paint;)V", "line_numbers": [ "4823", "4824", "4826", "4827", "4828" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "setDomainCrosshairValue", "be_test_function_signature": "(DZ)V", "line_numbers": [ "4765", "4766", "4767", "4769" ], "method_line_rate": 0.75 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "setDomainGridlinePaint", "be_test_function_signature": "(Ljava/awt/Paint;)V", "line_numbers": [ "1960", "1961", "1963", "1964", "1965" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "setDomainZeroBaselinePaint", "be_test_function_signature": "(Ljava/awt/Paint;)V", "line_numbers": [ "2272", "2273", "2275", "2276", "2277" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "setRangeCrosshairPaint", "be_test_function_signature": "(Ljava/awt/Paint;)V", "line_numbers": [ "4980", "4981", "4983", "4984", "4985" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "setRangeCrosshairValue", "be_test_function_signature": "(DZ)V", "line_numbers": [ "4922", "4923", "4924", "4926" ], "method_line_rate": 0.75 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "setRangeGridlinePaint", "be_test_function_signature": "(Ljava/awt/Paint;)V", "line_numbers": [ "2081", "2082", "2084", "2085", "2086" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/jfree/chart/plot/XYPlot.java", "be_test_class_name": "org.jfree.chart.plot.XYPlot", "be_test_function_name": "setRangeZeroBaselinePaint", "be_test_function_signature": "(Ljava/awt/Paint;)V", "line_numbers": [ "2353", "2354", "2356", "2357", "2358" ], "method_line_rate": 0.8 }, { "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 ZipFileTest
@Test public void testReadingOfFirstStoredEntry() throws Exception { final File archive = getFile("COMPRESS-264.zip"); zf = new ZipFile(archive); final ZipArchiveEntry ze = zf.getEntry("test.txt"); assertEquals(5, ze.getSize()); assertArrayEquals(new byte[] {'d', 'a', 't', 'a', '\n'}, IOUtils.toByteArray(zf.getInputStream(ze))); }
// public InputStream getInputStream(final ZipArchiveEntry ze) // throws IOException, ZipException; // public String getUnixSymlink(final ZipArchiveEntry entry) throws IOException; // @Override // protected void finalize() throws Throwable; // private Map<ZipArchiveEntry, NameAndComment> populateFromCentralDirectory() // throws IOException; // private void // readCentralDirectoryEntry(final Map<ZipArchiveEntry, NameAndComment> noUTF8Flag) // throws IOException; // private void setSizesAndOffsetFromZip64Extra(final ZipArchiveEntry ze, // final int diskStart) // throws IOException; // private void positionAtCentralDirectory() // throws IOException; // private void positionAtCentralDirectory64() // throws IOException; // private void positionAtCentralDirectory32() // throws IOException; // private void positionAtEndOfCentralDirectoryRecord() // throws IOException; // private boolean tryToLocateSignature(final long minDistanceFromEnd, // final long maxDistanceFromEnd, // final byte[] sig) throws IOException; // private void skipBytes(final int count) throws IOException; // private void resolveLocalFileHeaderData(final Map<ZipArchiveEntry, NameAndComment> // entriesWithoutUTF8Flag) // throws IOException; // private boolean startsWithLocalFileHeader() throws IOException; // private BoundedInputStream createBoundedInputStream(long start, long remaining); // BoundedInputStream(final long start, final long remaining); // @Override // public synchronized int read() throws IOException; // @Override // public synchronized int read(final byte[] b, final int off, int len) throws IOException; // protected int read(long pos, ByteBuffer buf) throws IOException; // synchronized void addDummy(); // BoundedFileChannelInputStream(final long start, final long remaining); // @Override // protected int read(long pos, ByteBuffer buf) throws IOException; // private NameAndComment(final byte[] name, final byte[] comment); // Entry(); // @Override // public int hashCode(); // @Override // public boolean equals(final Object other); // @Override // public int compare(final ZipArchiveEntry e1, final ZipArchiveEntry e2); // @Override // public void close() 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.*; // import java.io.ByteArrayOutputStream; // import java.io.File; // import java.io.FileInputStream; // import java.io.FileOutputStream; // import java.io.IOException; // import java.io.InputStream; // import java.io.OutputStream; // import java.nio.charset.Charset; // import java.util.ArrayList; // import java.util.Arrays; // import java.util.Collections; // import java.util.Enumeration; // import java.util.HashMap; // import java.util.Map; // import java.util.TreeMap; // import java.util.concurrent.atomic.AtomicInteger; // import java.util.zip.CRC32; // import java.util.zip.ZipEntry; // import org.apache.commons.compress.utils.IOUtils; // import org.apache.commons.compress.utils.SeekableInMemoryByteChannel; // import org.junit.After; // import org.junit.Assert; // import org.junit.Test; // // // // public class ZipFileTest { // private ZipFile zf = null; // // @After // public void tearDown(); // @Test // public void testCDOrder() throws Exception; // @Test // public void testCDOrderInMemory() throws Exception; // @Test // public void testPhysicalOrder() throws Exception; // @Test // public void testDoubleClose() throws Exception; // @Test // public void testReadingOfStoredEntry() throws Exception; // @Test // public void testWinzipBackSlashWorkaround() throws Exception; // @Test // public void testSkipsPK00Prefix() throws Exception; // @Test // public void testUnixSymlinkSampleFile() throws Exception; // @Test // public void testDuplicateEntry() throws Exception; // @Test // public void testExcessDataInZip64ExtraField() throws Exception; // @Test // public void testUnshrinking() throws Exception; // @Test // public void testReadingOfFirstStoredEntry() throws Exception; // @Test // public void testUnzipBZip2CompressedEntry() throws Exception; // @Test // public void testConcurrentReadSeekable() throws Exception; // @Test // public void testConcurrentReadFile() throws Exception; // @Test // public void testOffsets() throws Exception; // @Test // public void testDelayedOffsetsAndSizes() throws Exception; // @Test // public void testEntryAlignment() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testEntryAlignmentExceed() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testInvalidAlignment() throws Exception; // @Test // public void nameSourceDefaultsToName() throws Exception; // @Test // public void nameSourceIsSetToUnicodeExtraField() throws Exception; // @Test // public void nameSourceIsSetToEFS() throws Exception; // @Test // public void readDeflate64CompressedStream() throws Exception; // private void assertAllReadMethods(byte[] expected, ZipFile zipFile, ZipArchiveEntry entry); // private byte[] readStreamRest(byte[] beginning, int length, InputStream stream) throws IOException; // private long calculateCrc32(byte[] content); // private void readOrderTest() throws Exception; // private static void assertEntryName(final ArrayList<ZipArchiveEntry> entries, // final int index, // final String expectedName); // private static void nameSource(String archive, String entry, ZipArchiveEntry.NameSource expected) throws Exception; // @Override // public void run(); // @Override // public void run(); // } // You are a professional Java test case writer, please create a test case named `testReadingOfFirstStoredEntry` for the `ZipFile` 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-264" * >COMPRESS-264</a>. */
src/test/java/org/apache/commons/compress/archivers/zip/ZipFileTest.java
package org.apache.commons.compress.archivers.zip; import java.io.BufferedInputStream; import java.io.Closeable; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SeekableByteChannel; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; import java.util.zip.ZipException; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; import org.apache.commons.compress.compressors.deflate64.Deflate64CompressorInputStream; 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; import static org.apache.commons.compress.archivers.zip.ZipConstants.ZIP64_MAGIC_SHORT;
public ZipFile(final File f) throws IOException; public ZipFile(final String name) throws IOException; public ZipFile(final String name, final String encoding) throws IOException; public ZipFile(final File f, final String encoding) throws IOException; public ZipFile(final File f, final String encoding, final boolean useUnicodeExtraFields) throws IOException; public ZipFile(final SeekableByteChannel channel) throws IOException; public ZipFile(final SeekableByteChannel channel, final String encoding) throws IOException; public ZipFile(final SeekableByteChannel channel, final String archiveName, final String encoding, final boolean useUnicodeExtraFields) throws IOException; private ZipFile(final SeekableByteChannel channel, final String archiveName, final String encoding, final boolean useUnicodeExtraFields, final boolean closeOnError) throws IOException; public String getEncoding(); @Override public void close() throws IOException; public static void closeQuietly(final ZipFile zipfile); public Enumeration<ZipArchiveEntry> getEntries(); public Enumeration<ZipArchiveEntry> getEntriesInPhysicalOrder(); public ZipArchiveEntry getEntry(final String name); public Iterable<ZipArchiveEntry> getEntries(final String name); public Iterable<ZipArchiveEntry> getEntriesInPhysicalOrder(final String name); public boolean canReadEntryData(final ZipArchiveEntry ze); public InputStream getRawInputStream(final ZipArchiveEntry ze); public void copyRawEntries(final ZipArchiveOutputStream target, final ZipArchiveEntryPredicate predicate) throws IOException; public InputStream getInputStream(final ZipArchiveEntry ze) throws IOException, ZipException; public String getUnixSymlink(final ZipArchiveEntry entry) throws IOException; @Override protected void finalize() throws Throwable; private Map<ZipArchiveEntry, NameAndComment> populateFromCentralDirectory() throws IOException; private void readCentralDirectoryEntry(final Map<ZipArchiveEntry, NameAndComment> noUTF8Flag) throws IOException; private void setSizesAndOffsetFromZip64Extra(final ZipArchiveEntry ze, final int diskStart) throws IOException; private void positionAtCentralDirectory() throws IOException; private void positionAtCentralDirectory64() throws IOException; private void positionAtCentralDirectory32() throws IOException; private void positionAtEndOfCentralDirectoryRecord() throws IOException; private boolean tryToLocateSignature(final long minDistanceFromEnd, final long maxDistanceFromEnd, final byte[] sig) throws IOException; private void skipBytes(final int count) throws IOException; private void resolveLocalFileHeaderData(final Map<ZipArchiveEntry, NameAndComment> entriesWithoutUTF8Flag) throws IOException; private boolean startsWithLocalFileHeader() throws IOException; private BoundedInputStream createBoundedInputStream(long start, long remaining); BoundedInputStream(final long start, final long remaining); @Override public synchronized int read() throws IOException; @Override public synchronized int read(final byte[] b, final int off, int len) throws IOException; protected int read(long pos, ByteBuffer buf) throws IOException; synchronized void addDummy(); BoundedFileChannelInputStream(final long start, final long remaining); @Override protected int read(long pos, ByteBuffer buf) throws IOException; private NameAndComment(final byte[] name, final byte[] comment); Entry(); @Override public int hashCode(); @Override public boolean equals(final Object other); @Override public int compare(final ZipArchiveEntry e1, final ZipArchiveEntry e2); @Override public void close() throws IOException;
328
testReadingOfFirstStoredEntry
```java public InputStream getInputStream(final ZipArchiveEntry ze) throws IOException, ZipException; public String getUnixSymlink(final ZipArchiveEntry entry) throws IOException; @Override protected void finalize() throws Throwable; private Map<ZipArchiveEntry, NameAndComment> populateFromCentralDirectory() throws IOException; private void readCentralDirectoryEntry(final Map<ZipArchiveEntry, NameAndComment> noUTF8Flag) throws IOException; private void setSizesAndOffsetFromZip64Extra(final ZipArchiveEntry ze, final int diskStart) throws IOException; private void positionAtCentralDirectory() throws IOException; private void positionAtCentralDirectory64() throws IOException; private void positionAtCentralDirectory32() throws IOException; private void positionAtEndOfCentralDirectoryRecord() throws IOException; private boolean tryToLocateSignature(final long minDistanceFromEnd, final long maxDistanceFromEnd, final byte[] sig) throws IOException; private void skipBytes(final int count) throws IOException; private void resolveLocalFileHeaderData(final Map<ZipArchiveEntry, NameAndComment> entriesWithoutUTF8Flag) throws IOException; private boolean startsWithLocalFileHeader() throws IOException; private BoundedInputStream createBoundedInputStream(long start, long remaining); BoundedInputStream(final long start, final long remaining); @Override public synchronized int read() throws IOException; @Override public synchronized int read(final byte[] b, final int off, int len) throws IOException; protected int read(long pos, ByteBuffer buf) throws IOException; synchronized void addDummy(); BoundedFileChannelInputStream(final long start, final long remaining); @Override protected int read(long pos, ByteBuffer buf) throws IOException; private NameAndComment(final byte[] name, final byte[] comment); Entry(); @Override public int hashCode(); @Override public boolean equals(final Object other); @Override public int compare(final ZipArchiveEntry e1, final ZipArchiveEntry e2); @Override public void close() 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.*; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.compress.utils.SeekableInMemoryByteChannel; import org.junit.After; import org.junit.Assert; import org.junit.Test; public class ZipFileTest { private ZipFile zf = null; @After public void tearDown(); @Test public void testCDOrder() throws Exception; @Test public void testCDOrderInMemory() throws Exception; @Test public void testPhysicalOrder() throws Exception; @Test public void testDoubleClose() throws Exception; @Test public void testReadingOfStoredEntry() throws Exception; @Test public void testWinzipBackSlashWorkaround() throws Exception; @Test public void testSkipsPK00Prefix() throws Exception; @Test public void testUnixSymlinkSampleFile() throws Exception; @Test public void testDuplicateEntry() throws Exception; @Test public void testExcessDataInZip64ExtraField() throws Exception; @Test public void testUnshrinking() throws Exception; @Test public void testReadingOfFirstStoredEntry() throws Exception; @Test public void testUnzipBZip2CompressedEntry() throws Exception; @Test public void testConcurrentReadSeekable() throws Exception; @Test public void testConcurrentReadFile() throws Exception; @Test public void testOffsets() throws Exception; @Test public void testDelayedOffsetsAndSizes() throws Exception; @Test public void testEntryAlignment() throws Exception; @Test(expected = IllegalArgumentException.class) public void testEntryAlignmentExceed() throws Exception; @Test(expected = IllegalArgumentException.class) public void testInvalidAlignment() throws Exception; @Test public void nameSourceDefaultsToName() throws Exception; @Test public void nameSourceIsSetToUnicodeExtraField() throws Exception; @Test public void nameSourceIsSetToEFS() throws Exception; @Test public void readDeflate64CompressedStream() throws Exception; private void assertAllReadMethods(byte[] expected, ZipFile zipFile, ZipArchiveEntry entry); private byte[] readStreamRest(byte[] beginning, int length, InputStream stream) throws IOException; private long calculateCrc32(byte[] content); private void readOrderTest() throws Exception; private static void assertEntryName(final ArrayList<ZipArchiveEntry> entries, final int index, final String expectedName); private static void nameSource(String archive, String entry, ZipArchiveEntry.NameSource expected) throws Exception; @Override public void run(); @Override public void run(); } ``` You are a professional Java test case writer, please create a test case named `testReadingOfFirstStoredEntry` for the `ZipFile` 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-264" * >COMPRESS-264</a>. */
320
// public InputStream getInputStream(final ZipArchiveEntry ze) // throws IOException, ZipException; // public String getUnixSymlink(final ZipArchiveEntry entry) throws IOException; // @Override // protected void finalize() throws Throwable; // private Map<ZipArchiveEntry, NameAndComment> populateFromCentralDirectory() // throws IOException; // private void // readCentralDirectoryEntry(final Map<ZipArchiveEntry, NameAndComment> noUTF8Flag) // throws IOException; // private void setSizesAndOffsetFromZip64Extra(final ZipArchiveEntry ze, // final int diskStart) // throws IOException; // private void positionAtCentralDirectory() // throws IOException; // private void positionAtCentralDirectory64() // throws IOException; // private void positionAtCentralDirectory32() // throws IOException; // private void positionAtEndOfCentralDirectoryRecord() // throws IOException; // private boolean tryToLocateSignature(final long minDistanceFromEnd, // final long maxDistanceFromEnd, // final byte[] sig) throws IOException; // private void skipBytes(final int count) throws IOException; // private void resolveLocalFileHeaderData(final Map<ZipArchiveEntry, NameAndComment> // entriesWithoutUTF8Flag) // throws IOException; // private boolean startsWithLocalFileHeader() throws IOException; // private BoundedInputStream createBoundedInputStream(long start, long remaining); // BoundedInputStream(final long start, final long remaining); // @Override // public synchronized int read() throws IOException; // @Override // public synchronized int read(final byte[] b, final int off, int len) throws IOException; // protected int read(long pos, ByteBuffer buf) throws IOException; // synchronized void addDummy(); // BoundedFileChannelInputStream(final long start, final long remaining); // @Override // protected int read(long pos, ByteBuffer buf) throws IOException; // private NameAndComment(final byte[] name, final byte[] comment); // Entry(); // @Override // public int hashCode(); // @Override // public boolean equals(final Object other); // @Override // public int compare(final ZipArchiveEntry e1, final ZipArchiveEntry e2); // @Override // public void close() 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.*; // import java.io.ByteArrayOutputStream; // import java.io.File; // import java.io.FileInputStream; // import java.io.FileOutputStream; // import java.io.IOException; // import java.io.InputStream; // import java.io.OutputStream; // import java.nio.charset.Charset; // import java.util.ArrayList; // import java.util.Arrays; // import java.util.Collections; // import java.util.Enumeration; // import java.util.HashMap; // import java.util.Map; // import java.util.TreeMap; // import java.util.concurrent.atomic.AtomicInteger; // import java.util.zip.CRC32; // import java.util.zip.ZipEntry; // import org.apache.commons.compress.utils.IOUtils; // import org.apache.commons.compress.utils.SeekableInMemoryByteChannel; // import org.junit.After; // import org.junit.Assert; // import org.junit.Test; // // // // public class ZipFileTest { // private ZipFile zf = null; // // @After // public void tearDown(); // @Test // public void testCDOrder() throws Exception; // @Test // public void testCDOrderInMemory() throws Exception; // @Test // public void testPhysicalOrder() throws Exception; // @Test // public void testDoubleClose() throws Exception; // @Test // public void testReadingOfStoredEntry() throws Exception; // @Test // public void testWinzipBackSlashWorkaround() throws Exception; // @Test // public void testSkipsPK00Prefix() throws Exception; // @Test // public void testUnixSymlinkSampleFile() throws Exception; // @Test // public void testDuplicateEntry() throws Exception; // @Test // public void testExcessDataInZip64ExtraField() throws Exception; // @Test // public void testUnshrinking() throws Exception; // @Test // public void testReadingOfFirstStoredEntry() throws Exception; // @Test // public void testUnzipBZip2CompressedEntry() throws Exception; // @Test // public void testConcurrentReadSeekable() throws Exception; // @Test // public void testConcurrentReadFile() throws Exception; // @Test // public void testOffsets() throws Exception; // @Test // public void testDelayedOffsetsAndSizes() throws Exception; // @Test // public void testEntryAlignment() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testEntryAlignmentExceed() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testInvalidAlignment() throws Exception; // @Test // public void nameSourceDefaultsToName() throws Exception; // @Test // public void nameSourceIsSetToUnicodeExtraField() throws Exception; // @Test // public void nameSourceIsSetToEFS() throws Exception; // @Test // public void readDeflate64CompressedStream() throws Exception; // private void assertAllReadMethods(byte[] expected, ZipFile zipFile, ZipArchiveEntry entry); // private byte[] readStreamRest(byte[] beginning, int length, InputStream stream) throws IOException; // private long calculateCrc32(byte[] content); // private void readOrderTest() throws Exception; // private static void assertEntryName(final ArrayList<ZipArchiveEntry> entries, // final int index, // final String expectedName); // private static void nameSource(String archive, String entry, ZipArchiveEntry.NameSource expected) throws Exception; // @Override // public void run(); // @Override // public void run(); // } // You are a professional Java test case writer, please create a test case named `testReadingOfFirstStoredEntry` for the `ZipFile` 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-264" * >COMPRESS-264</a>. */ @Test public void testReadingOfFirstStoredEntry() throws Exception {
/** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-264" * >COMPRESS-264</a>. */
47
org.apache.commons.compress.archivers.zip.ZipFile
src/test/java
```java public InputStream getInputStream(final ZipArchiveEntry ze) throws IOException, ZipException; public String getUnixSymlink(final ZipArchiveEntry entry) throws IOException; @Override protected void finalize() throws Throwable; private Map<ZipArchiveEntry, NameAndComment> populateFromCentralDirectory() throws IOException; private void readCentralDirectoryEntry(final Map<ZipArchiveEntry, NameAndComment> noUTF8Flag) throws IOException; private void setSizesAndOffsetFromZip64Extra(final ZipArchiveEntry ze, final int diskStart) throws IOException; private void positionAtCentralDirectory() throws IOException; private void positionAtCentralDirectory64() throws IOException; private void positionAtCentralDirectory32() throws IOException; private void positionAtEndOfCentralDirectoryRecord() throws IOException; private boolean tryToLocateSignature(final long minDistanceFromEnd, final long maxDistanceFromEnd, final byte[] sig) throws IOException; private void skipBytes(final int count) throws IOException; private void resolveLocalFileHeaderData(final Map<ZipArchiveEntry, NameAndComment> entriesWithoutUTF8Flag) throws IOException; private boolean startsWithLocalFileHeader() throws IOException; private BoundedInputStream createBoundedInputStream(long start, long remaining); BoundedInputStream(final long start, final long remaining); @Override public synchronized int read() throws IOException; @Override public synchronized int read(final byte[] b, final int off, int len) throws IOException; protected int read(long pos, ByteBuffer buf) throws IOException; synchronized void addDummy(); BoundedFileChannelInputStream(final long start, final long remaining); @Override protected int read(long pos, ByteBuffer buf) throws IOException; private NameAndComment(final byte[] name, final byte[] comment); Entry(); @Override public int hashCode(); @Override public boolean equals(final Object other); @Override public int compare(final ZipArchiveEntry e1, final ZipArchiveEntry e2); @Override public void close() 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.*; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.compress.utils.SeekableInMemoryByteChannel; import org.junit.After; import org.junit.Assert; import org.junit.Test; public class ZipFileTest { private ZipFile zf = null; @After public void tearDown(); @Test public void testCDOrder() throws Exception; @Test public void testCDOrderInMemory() throws Exception; @Test public void testPhysicalOrder() throws Exception; @Test public void testDoubleClose() throws Exception; @Test public void testReadingOfStoredEntry() throws Exception; @Test public void testWinzipBackSlashWorkaround() throws Exception; @Test public void testSkipsPK00Prefix() throws Exception; @Test public void testUnixSymlinkSampleFile() throws Exception; @Test public void testDuplicateEntry() throws Exception; @Test public void testExcessDataInZip64ExtraField() throws Exception; @Test public void testUnshrinking() throws Exception; @Test public void testReadingOfFirstStoredEntry() throws Exception; @Test public void testUnzipBZip2CompressedEntry() throws Exception; @Test public void testConcurrentReadSeekable() throws Exception; @Test public void testConcurrentReadFile() throws Exception; @Test public void testOffsets() throws Exception; @Test public void testDelayedOffsetsAndSizes() throws Exception; @Test public void testEntryAlignment() throws Exception; @Test(expected = IllegalArgumentException.class) public void testEntryAlignmentExceed() throws Exception; @Test(expected = IllegalArgumentException.class) public void testInvalidAlignment() throws Exception; @Test public void nameSourceDefaultsToName() throws Exception; @Test public void nameSourceIsSetToUnicodeExtraField() throws Exception; @Test public void nameSourceIsSetToEFS() throws Exception; @Test public void readDeflate64CompressedStream() throws Exception; private void assertAllReadMethods(byte[] expected, ZipFile zipFile, ZipArchiveEntry entry); private byte[] readStreamRest(byte[] beginning, int length, InputStream stream) throws IOException; private long calculateCrc32(byte[] content); private void readOrderTest() throws Exception; private static void assertEntryName(final ArrayList<ZipArchiveEntry> entries, final int index, final String expectedName); private static void nameSource(String archive, String entry, ZipArchiveEntry.NameSource expected) throws Exception; @Override public void run(); @Override public void run(); } ``` You are a professional Java test case writer, please create a test case named `testReadingOfFirstStoredEntry` for the `ZipFile` 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-264" * >COMPRESS-264</a>. */ @Test public void testReadingOfFirstStoredEntry() throws Exception { ```
public class ZipFile implements Closeable
package org.apache.commons.compress.archivers.zip; import static org.apache.commons.compress.AbstractTestCase.getFile; import static org.junit.Assert.*; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.compress.utils.SeekableInMemoryByteChannel; import org.junit.After; import org.junit.Assert; import org.junit.Test;
@After public void tearDown(); @Test public void testCDOrder() throws Exception; @Test public void testCDOrderInMemory() throws Exception; @Test public void testPhysicalOrder() throws Exception; @Test public void testDoubleClose() throws Exception; @Test public void testReadingOfStoredEntry() throws Exception; @Test public void testWinzipBackSlashWorkaround() throws Exception; @Test public void testSkipsPK00Prefix() throws Exception; @Test public void testUnixSymlinkSampleFile() throws Exception; @Test public void testDuplicateEntry() throws Exception; @Test public void testExcessDataInZip64ExtraField() throws Exception; @Test public void testUnshrinking() throws Exception; @Test public void testReadingOfFirstStoredEntry() throws Exception; @Test public void testUnzipBZip2CompressedEntry() throws Exception; @Test public void testConcurrentReadSeekable() throws Exception; @Test public void testConcurrentReadFile() throws Exception; @Test public void testOffsets() throws Exception; @Test public void testDelayedOffsetsAndSizes() throws Exception; @Test public void testEntryAlignment() throws Exception; @Test(expected = IllegalArgumentException.class) public void testEntryAlignmentExceed() throws Exception; @Test(expected = IllegalArgumentException.class) public void testInvalidAlignment() throws Exception; @Test public void nameSourceDefaultsToName() throws Exception; @Test public void nameSourceIsSetToUnicodeExtraField() throws Exception; @Test public void nameSourceIsSetToEFS() throws Exception; @Test public void readDeflate64CompressedStream() throws Exception; private void assertAllReadMethods(byte[] expected, ZipFile zipFile, ZipArchiveEntry entry); private byte[] readStreamRest(byte[] beginning, int length, InputStream stream) throws IOException; private long calculateCrc32(byte[] content); private void readOrderTest() throws Exception; private static void assertEntryName(final ArrayList<ZipArchiveEntry> entries, final int index, final String expectedName); private static void nameSource(String archive, String entry, ZipArchiveEntry.NameSource expected) throws Exception; @Override public void run(); @Override public void run();
9cca185a22be26faf343d59c734f865f78f3897e6a397fccf723778d00fce0d8
[ "org.apache.commons.compress.archivers.zip.ZipFileTest::testReadingOfFirstStoredEntry" ]
private static final int HASH_SIZE = 509; static final int NIBLET_MASK = 0x0f; static final int BYTE_SHIFT = 8; private static final int POS_0 = 0; private static final int POS_1 = 1; private static final int POS_2 = 2; private static final int POS_3 = 3; private final List<ZipArchiveEntry> entries = new LinkedList<>(); private final Map<String, LinkedList<ZipArchiveEntry>> nameMap = new HashMap<>(HASH_SIZE); private final String encoding; private final ZipEncoding zipEncoding; private final String archiveName; private final SeekableByteChannel archive; private final boolean useUnicodeExtraFields; private volatile boolean closed = true; private final byte[] dwordBuf = new byte[DWORD]; private final byte[] wordBuf = new byte[WORD]; private final byte[] cfhBuf = new byte[CFH_LEN]; private final byte[] shortBuf = new byte[SHORT]; private final ByteBuffer dwordBbuf = ByteBuffer.wrap(dwordBuf); private final ByteBuffer wordBbuf = ByteBuffer.wrap(wordBuf); private final ByteBuffer cfhBbuf = ByteBuffer.wrap(cfhBuf); private static final int CFH_LEN = /* version made by */ SHORT /* version needed to extract */ + SHORT /* general purpose bit flag */ + SHORT /* compression method */ + SHORT /* last mod file time */ + SHORT /* last mod file date */ + SHORT /* crc-32 */ + WORD /* compressed size */ + WORD /* uncompressed size */ + WORD /* filename length */ + SHORT /* extra field length */ + SHORT /* file comment length */ + SHORT /* disk number start */ + SHORT /* internal file attributes */ + SHORT /* external file attributes */ + WORD /* relative offset of local header */ + WORD; private static final long CFH_SIG = ZipLong.getValue(ZipArchiveOutputStream.CFH_SIG); static final int MIN_EOCD_SIZE = /* end of central dir signature */ WORD /* number of this disk */ + SHORT /* number of the disk with the */ /* start of the central directory */ + SHORT /* total number of entries in */ /* the central dir on this disk */ + SHORT /* total number of entries in */ /* the central dir */ + SHORT /* size of the central directory */ + WORD /* offset of start of central */ /* directory with respect to */ /* the starting disk number */ + WORD /* zipfile comment length */ + SHORT; private static final int MAX_EOCD_SIZE = MIN_EOCD_SIZE /* maximum length of zipfile comment */ + ZIP64_MAGIC_SHORT; private static final int CFD_LOCATOR_OFFSET = /* end of central dir signature */ WORD /* number of this disk */ + SHORT /* number of the disk with the */ /* start of the central directory */ + SHORT /* total number of entries in */ /* the central dir on this disk */ + SHORT /* total number of entries in */ /* the central dir */ + SHORT /* size of the central directory */ + WORD; private static final int ZIP64_EOCDL_LENGTH = /* zip64 end of central dir locator sig */ WORD /* number of the disk with the start */ /* start of the zip64 end of */ /* central directory */ + WORD /* relative offset of the zip64 */ /* end of central directory record */ + DWORD /* total number of disks */ + WORD; private static final int ZIP64_EOCDL_LOCATOR_OFFSET = /* zip64 end of central dir locator sig */ WORD /* number of the disk with the start */ /* start of the zip64 end of */ /* central directory */ + WORD; private static final int ZIP64_EOCD_CFD_LOCATOR_OFFSET = /* zip64 end of central dir */ /* signature */ WORD /* size of zip64 end of central */ /* directory record */ + DWORD /* version made by */ + SHORT /* version needed to extract */ + SHORT /* number of this disk */ + WORD /* number of the disk with the */ /* start of the central directory */ + WORD /* total number of entries in the */ /* central directory on this disk */ + DWORD /* total number of entries in the */ /* central directory */ + DWORD /* size of the central directory */ + DWORD; private static final long LFH_OFFSET_FOR_FILENAME_LENGTH = /* local file header signature */ WORD /* version needed to extract */ + SHORT /* general purpose bit flag */ + SHORT /* compression method */ + SHORT /* last mod file time */ + SHORT /* last mod file date */ + SHORT /* crc-32 */ + WORD /* compressed size */ + WORD /* uncompressed size */ + (long) WORD; private final Comparator<ZipArchiveEntry> offsetComparator = new Comparator<ZipArchiveEntry>() { @Override public int compare(final ZipArchiveEntry e1, final ZipArchiveEntry e2) { if (e1 == e2) { return 0; } final Entry ent1 = e1 instanceof Entry ? (Entry) e1 : null; final Entry ent2 = e2 instanceof Entry ? (Entry) e2 : null; if (ent1 == null) { return 1; } if (ent2 == null) { return -1; } final long val = (ent1.getLocalHeaderOffset() - ent2.getLocalHeaderOffset()); return val == 0 ? 0 : val < 0 ? -1 : +1; } };
@Test public void testReadingOfFirstStoredEntry() throws Exception
private ZipFile zf = null;
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.*; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.compress.utils.SeekableInMemoryByteChannel; import org.junit.After; import org.junit.Assert; import org.junit.Test; public class ZipFileTest { private ZipFile zf = null; @After public void tearDown() { ZipFile.closeQuietly(zf); } @Test public void testCDOrder() throws Exception { readOrderTest(); final ArrayList<ZipArchiveEntry> l = Collections.list(zf.getEntries()); assertEntryName(l, 0, "AbstractUnicodeExtraField"); assertEntryName(l, 1, "AsiExtraField"); assertEntryName(l, 2, "ExtraFieldUtils"); assertEntryName(l, 3, "FallbackZipEncoding"); assertEntryName(l, 4, "GeneralPurposeBit"); assertEntryName(l, 5, "JarMarker"); assertEntryName(l, 6, "NioZipEncoding"); assertEntryName(l, 7, "Simple8BitZipEncoding"); assertEntryName(l, 8, "UnicodeCommentExtraField"); assertEntryName(l, 9, "UnicodePathExtraField"); assertEntryName(l, 10, "UnixStat"); assertEntryName(l, 11, "UnparseableExtraFieldData"); assertEntryName(l, 12, "UnrecognizedExtraField"); assertEntryName(l, 13, "ZipArchiveEntry"); assertEntryName(l, 14, "ZipArchiveInputStream"); assertEntryName(l, 15, "ZipArchiveOutputStream"); assertEntryName(l, 16, "ZipEncoding"); assertEntryName(l, 17, "ZipEncodingHelper"); assertEntryName(l, 18, "ZipExtraField"); assertEntryName(l, 19, "ZipUtil"); assertEntryName(l, 20, "ZipLong"); assertEntryName(l, 21, "ZipShort"); assertEntryName(l, 22, "ZipFile"); } @Test public void testCDOrderInMemory() throws Exception { byte[] data = null; try (FileInputStream fis = new FileInputStream(getFile("ordertest.zip"))) { data = IOUtils.toByteArray(fis); } zf = new ZipFile(new SeekableInMemoryByteChannel(data), ZipEncodingHelper.UTF8); final ArrayList<ZipArchiveEntry> l = Collections.list(zf.getEntries()); assertEntryName(l, 0, "AbstractUnicodeExtraField"); assertEntryName(l, 1, "AsiExtraField"); assertEntryName(l, 2, "ExtraFieldUtils"); assertEntryName(l, 3, "FallbackZipEncoding"); assertEntryName(l, 4, "GeneralPurposeBit"); assertEntryName(l, 5, "JarMarker"); assertEntryName(l, 6, "NioZipEncoding"); assertEntryName(l, 7, "Simple8BitZipEncoding"); assertEntryName(l, 8, "UnicodeCommentExtraField"); assertEntryName(l, 9, "UnicodePathExtraField"); assertEntryName(l, 10, "UnixStat"); assertEntryName(l, 11, "UnparseableExtraFieldData"); assertEntryName(l, 12, "UnrecognizedExtraField"); assertEntryName(l, 13, "ZipArchiveEntry"); assertEntryName(l, 14, "ZipArchiveInputStream"); assertEntryName(l, 15, "ZipArchiveOutputStream"); assertEntryName(l, 16, "ZipEncoding"); assertEntryName(l, 17, "ZipEncodingHelper"); assertEntryName(l, 18, "ZipExtraField"); assertEntryName(l, 19, "ZipUtil"); assertEntryName(l, 20, "ZipLong"); assertEntryName(l, 21, "ZipShort"); assertEntryName(l, 22, "ZipFile"); } @Test public void testPhysicalOrder() throws Exception { readOrderTest(); final ArrayList<ZipArchiveEntry> l = Collections.list(zf.getEntriesInPhysicalOrder()); assertEntryName(l, 0, "AbstractUnicodeExtraField"); assertEntryName(l, 1, "AsiExtraField"); assertEntryName(l, 2, "ExtraFieldUtils"); assertEntryName(l, 3, "FallbackZipEncoding"); assertEntryName(l, 4, "GeneralPurposeBit"); assertEntryName(l, 5, "JarMarker"); assertEntryName(l, 6, "NioZipEncoding"); assertEntryName(l, 7, "Simple8BitZipEncoding"); assertEntryName(l, 8, "UnicodeCommentExtraField"); assertEntryName(l, 9, "UnicodePathExtraField"); assertEntryName(l, 10, "UnixStat"); assertEntryName(l, 11, "UnparseableExtraFieldData"); assertEntryName(l, 12, "UnrecognizedExtraField"); assertEntryName(l, 13, "ZipArchiveEntry"); assertEntryName(l, 14, "ZipArchiveInputStream"); assertEntryName(l, 15, "ZipArchiveOutputStream"); assertEntryName(l, 16, "ZipEncoding"); assertEntryName(l, 17, "ZipEncodingHelper"); assertEntryName(l, 18, "ZipExtraField"); assertEntryName(l, 19, "ZipFile"); assertEntryName(l, 20, "ZipLong"); assertEntryName(l, 21, "ZipShort"); assertEntryName(l, 22, "ZipUtil"); } @Test public void testDoubleClose() throws Exception { readOrderTest(); zf.close(); try { zf.close(); } catch (final Exception ex) { fail("Caught exception of second close"); } } @Test public void testReadingOfStoredEntry() throws Exception { final File f = File.createTempFile("commons-compress-zipfiletest", ".zip"); f.deleteOnExit(); OutputStream o = null; InputStream i = null; try { o = new FileOutputStream(f); final ZipArchiveOutputStream zo = new ZipArchiveOutputStream(o); ZipArchiveEntry ze = new ZipArchiveEntry("foo"); ze.setMethod(ZipEntry.STORED); ze.setSize(4); ze.setCrc(0xb63cfbcdl); zo.putArchiveEntry(ze); zo.write(new byte[] { 1, 2, 3, 4 }); zo.closeArchiveEntry(); zo.close(); o.close(); o = null; zf = new ZipFile(f); ze = zf.getEntry("foo"); assertNotNull(ze); i = zf.getInputStream(ze); final byte[] b = new byte[4]; assertEquals(4, i.read(b)); assertEquals(-1, i.read()); } finally { if (o != null) { o.close(); } if (i != null) { i.close(); } f.delete(); } } /** * @see "https://issues.apache.org/jira/browse/COMPRESS-176" */ @Test public void testWinzipBackSlashWorkaround() throws Exception { final File archive = getFile("test-winzip.zip"); zf = new ZipFile(archive); assertNull(zf.getEntry("\u00e4\\\u00fc.txt")); assertNotNull(zf.getEntry("\u00e4/\u00fc.txt")); } /** * Test case for * <a href="https://issues.apache.org/jira/browse/COMPRESS-208" * >COMPRESS-208</a>. */ @Test public void testSkipsPK00Prefix() throws Exception { final File archive = getFile("COMPRESS-208.zip"); zf = new ZipFile(archive); assertNotNull(zf.getEntry("test1.xml")); assertNotNull(zf.getEntry("test2.xml")); } @Test public void testUnixSymlinkSampleFile() throws Exception { final String entryPrefix = "COMPRESS-214_unix_symlinks/"; final TreeMap<String, String> expectedVals = new TreeMap<>(); // I threw in some Japanese characters to keep things interesting. expectedVals.put(entryPrefix + "link1", "../COMPRESS-214_unix_symlinks/./a/b/c/../../../\uF999"); expectedVals.put(entryPrefix + "link2", "../COMPRESS-214_unix_symlinks/./a/b/c/../../../g"); expectedVals.put(entryPrefix + "link3", "../COMPRESS-214_unix_symlinks/././a/b/c/../../../\u76F4\u6A39"); expectedVals.put(entryPrefix + "link4", "\u82B1\u5B50/\u745B\u5B50"); expectedVals.put(entryPrefix + "\uF999", "./\u82B1\u5B50/\u745B\u5B50/\u5897\u8C37/\uF999"); expectedVals.put(entryPrefix + "g", "./a/b/c/d/e/f/g"); expectedVals.put(entryPrefix + "\u76F4\u6A39", "./g"); // Notice how a directory link might contain a trailing slash, or it might not. // Also note: symlinks are always stored as files, even if they link to directories. expectedVals.put(entryPrefix + "link5", "../COMPRESS-214_unix_symlinks/././a/b"); expectedVals.put(entryPrefix + "link6", "../COMPRESS-214_unix_symlinks/././a/b/"); // I looked into creating a test with hard links, but zip does not appear to // support hard links, so nevermind. final File archive = getFile("COMPRESS-214_unix_symlinks.zip"); zf = new ZipFile(archive); final Enumeration<ZipArchiveEntry> en = zf.getEntries(); while (en.hasMoreElements()) { final ZipArchiveEntry zae = en.nextElement(); final String link = zf.getUnixSymlink(zae); if (zae.isUnixSymlink()) { final String name = zae.getName(); final String expected = expectedVals.get(name); assertEquals(expected, link); } else { // Should be null if it's not a symlink! assertNull(link); } } } /** * @see "https://issues.apache.org/jira/browse/COMPRESS-227" */ @Test public void testDuplicateEntry() throws Exception { final File archive = getFile("COMPRESS-227.zip"); zf = new ZipFile(archive); final ZipArchiveEntry ze = zf.getEntry("test1.txt"); assertNotNull(ze); assertNotNull(zf.getInputStream(ze)); int numberOfEntries = 0; for (final ZipArchiveEntry entry : zf.getEntries("test1.txt")) { numberOfEntries++; assertNotNull(zf.getInputStream(entry)); } assertEquals(2, numberOfEntries); } /** * @see "https://issues.apache.org/jira/browse/COMPRESS-228" */ @Test public void testExcessDataInZip64ExtraField() throws Exception { final File archive = getFile("COMPRESS-228.zip"); zf = new ZipFile(archive); // actually, if we get here, the test already has passed final ZipArchiveEntry ze = zf.getEntry("src/main/java/org/apache/commons/compress/archivers/zip/ZipFile.java"); assertEquals(26101, ze.getSize()); } @Test public void testUnshrinking() throws Exception { zf = new ZipFile(getFile("SHRUNK.ZIP")); ZipArchiveEntry test = zf.getEntry("TEST1.XML"); FileInputStream original = new FileInputStream(getFile("test1.xml")); try { assertArrayEquals(IOUtils.toByteArray(original), IOUtils.toByteArray(zf.getInputStream(test))); } finally { original.close(); } test = zf.getEntry("TEST2.XML"); original = new FileInputStream(getFile("test2.xml")); try { assertArrayEquals(IOUtils.toByteArray(original), IOUtils.toByteArray(zf.getInputStream(test))); } 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 { final File archive = getFile("COMPRESS-264.zip"); zf = new ZipFile(archive); final ZipArchiveEntry ze = zf.getEntry("test.txt"); assertEquals(5, ze.getSize()); assertArrayEquals(new byte[] {'d', 'a', 't', 'a', '\n'}, IOUtils.toByteArray(zf.getInputStream(ze))); } @Test public void testUnzipBZip2CompressedEntry() throws Exception { final File archive = getFile("bzip2-zip.zip"); zf = new ZipFile(archive); final ZipArchiveEntry ze = zf.getEntry("lots-of-as"); assertEquals(42, ze.getSize()); final byte[] expected = new byte[42]; Arrays.fill(expected , (byte)'a'); assertArrayEquals(expected, IOUtils.toByteArray(zf.getInputStream(ze))); } @Test public void testConcurrentReadSeekable() throws Exception { // mixed.zip contains both inflated and stored files byte[] data = null; try (FileInputStream fis = new FileInputStream(getFile("mixed.zip"))) { data = IOUtils.toByteArray(fis); } zf = new ZipFile(new SeekableInMemoryByteChannel(data), ZipEncodingHelper.UTF8); final Map<String, byte[]> content = new HashMap<String, byte[]>(); for (ZipArchiveEntry entry: Collections.list(zf.getEntries())) { content.put(entry.getName(), IOUtils.toByteArray(zf.getInputStream(entry))); } final AtomicInteger passedCount = new AtomicInteger(); Runnable run = new Runnable() { @Override public void run() { for (ZipArchiveEntry entry: Collections.list(zf.getEntries())) { assertAllReadMethods(content.get(entry.getName()), zf, entry); } passedCount.incrementAndGet(); } }; Thread t0 = new Thread(run); Thread t1 = new Thread(run); t0.start(); t1.start(); t0.join(); t1.join(); assertEquals(2, passedCount.get()); } @Test public void testConcurrentReadFile() throws Exception { // mixed.zip contains both inflated and stored files final File archive = getFile("mixed.zip"); zf = new ZipFile(archive); final Map<String, byte[]> content = new HashMap<String, byte[]>(); for (ZipArchiveEntry entry: Collections.list(zf.getEntries())) { content.put(entry.getName(), IOUtils.toByteArray(zf.getInputStream(entry))); } final AtomicInteger passedCount = new AtomicInteger(); Runnable run = new Runnable() { @Override public void run() { for (ZipArchiveEntry entry: Collections.list(zf.getEntries())) { assertAllReadMethods(content.get(entry.getName()), zf, entry); } passedCount.incrementAndGet(); } }; Thread t0 = new Thread(run); Thread t1 = new Thread(run); t0.start(); t1.start(); t0.join(); t1.join(); assertEquals(2, passedCount.get()); } /** * Test correct population of header and data offsets. */ @Test public void testOffsets() throws Exception { // mixed.zip contains both inflated and stored files final File archive = getFile("mixed.zip"); try (ZipFile zf = new ZipFile(archive)) { ZipArchiveEntry inflatedEntry = zf.getEntry("inflated.txt"); Assert.assertEquals(0x0000, inflatedEntry.getLocalHeaderOffset()); Assert.assertEquals(0x0046, inflatedEntry.getDataOffset()); Assert.assertTrue(inflatedEntry.isStreamContiguous()); ZipArchiveEntry storedEntry = zf.getEntry("stored.txt"); Assert.assertEquals(0x5892, storedEntry.getLocalHeaderOffset()); Assert.assertEquals(0x58d6, storedEntry.getDataOffset()); Assert.assertTrue(inflatedEntry.isStreamContiguous()); } } /** * Test correct population of header and data offsets when they are written after stream. */ @Test public void testDelayedOffsetsAndSizes() throws Exception { ByteArrayOutputStream zipContent = new ByteArrayOutputStream(); try (ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(zipContent)) { ZipArchiveEntry inflatedEntry = new ZipArchiveEntry("inflated.txt"); inflatedEntry.setMethod(ZipEntry.DEFLATED); zipOutput.putArchiveEntry(inflatedEntry); zipOutput.write("Hello Deflated\n".getBytes()); zipOutput.closeArchiveEntry(); byte[] storedContent = "Hello Stored\n".getBytes(); ZipArchiveEntry storedEntry = new ZipArchiveEntry("stored.txt"); storedEntry.setMethod(ZipEntry.STORED); storedEntry.setSize(storedContent.length); storedEntry.setCrc(calculateCrc32(storedContent)); zipOutput.putArchiveEntry(storedEntry); zipOutput.write("Hello Stored\n".getBytes()); zipOutput.closeArchiveEntry(); } try (ZipFile zf = new ZipFile(new SeekableInMemoryByteChannel(zipContent.toByteArray()))) { ZipArchiveEntry inflatedEntry = zf.getEntry("inflated.txt"); Assert.assertNotEquals(-1L, inflatedEntry.getLocalHeaderOffset()); Assert.assertNotEquals(-1L, inflatedEntry.getDataOffset()); Assert.assertTrue(inflatedEntry.isStreamContiguous()); Assert.assertNotEquals(-1L, inflatedEntry.getCompressedSize()); Assert.assertNotEquals(-1L, inflatedEntry.getSize()); ZipArchiveEntry storedEntry = zf.getEntry("stored.txt"); Assert.assertNotEquals(-1L, storedEntry.getLocalHeaderOffset()); Assert.assertNotEquals(-1L, storedEntry.getDataOffset()); Assert.assertTrue(inflatedEntry.isStreamContiguous()); Assert.assertNotEquals(-1L, storedEntry.getCompressedSize()); Assert.assertNotEquals(-1L, storedEntry.getSize()); } } /** * Test entries alignment. */ @Test public void testEntryAlignment() throws Exception { SeekableInMemoryByteChannel zipContent = new SeekableInMemoryByteChannel(); try (ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(zipContent)) { ZipArchiveEntry inflatedEntry = new ZipArchiveEntry("inflated.txt"); inflatedEntry.setMethod(ZipEntry.DEFLATED); inflatedEntry.setAlignment(1024); zipOutput.putArchiveEntry(inflatedEntry); zipOutput.write("Hello Deflated\n".getBytes(Charset.forName("UTF-8"))); zipOutput.closeArchiveEntry(); ZipArchiveEntry storedEntry = new ZipArchiveEntry("stored.txt"); storedEntry.setMethod(ZipEntry.STORED); storedEntry.setAlignment(1024); zipOutput.putArchiveEntry(storedEntry); zipOutput.write("Hello Stored\n".getBytes(Charset.forName("UTF-8"))); zipOutput.closeArchiveEntry(); ZipArchiveEntry storedEntry2 = new ZipArchiveEntry("stored2.txt"); storedEntry2.setMethod(ZipEntry.STORED); storedEntry2.setAlignment(1024); storedEntry2.addExtraField(new ResourceAlignmentExtraField(1)); zipOutput.putArchiveEntry(storedEntry2); zipOutput.write("Hello overload-alignment Stored\n".getBytes(Charset.forName("UTF-8"))); zipOutput.closeArchiveEntry(); ZipArchiveEntry storedEntry3 = new ZipArchiveEntry("stored3.txt"); storedEntry3.setMethod(ZipEntry.STORED); storedEntry3.addExtraField(new ResourceAlignmentExtraField(1024)); zipOutput.putArchiveEntry(storedEntry3); zipOutput.write("Hello copy-alignment Stored\n".getBytes(Charset.forName("UTF-8"))); zipOutput.closeArchiveEntry(); } try (ZipFile zf = new ZipFile(new SeekableInMemoryByteChannel( Arrays.copyOfRange(zipContent.array(), 0, (int)zipContent.size()) ))) { ZipArchiveEntry inflatedEntry = zf.getEntry("inflated.txt"); ResourceAlignmentExtraField inflatedAlignmentEx = (ResourceAlignmentExtraField)inflatedEntry.getExtraField(ResourceAlignmentExtraField.ID); assertNotEquals(-1L, inflatedEntry.getCompressedSize()); assertNotEquals(-1L, inflatedEntry.getSize()); assertEquals(0L, inflatedEntry.getDataOffset()%1024); assertNotNull(inflatedAlignmentEx); assertEquals(1024, inflatedAlignmentEx.getAlignment()); assertFalse(inflatedAlignmentEx.allowMethodChange()); try (InputStream stream = zf.getInputStream(inflatedEntry)) { Assert.assertEquals("Hello Deflated\n", new String(IOUtils.toByteArray(stream), Charset.forName("UTF-8"))); } ZipArchiveEntry storedEntry = zf.getEntry("stored.txt"); ResourceAlignmentExtraField storedAlignmentEx = (ResourceAlignmentExtraField)storedEntry.getExtraField(ResourceAlignmentExtraField.ID); assertNotEquals(-1L, storedEntry.getCompressedSize()); assertNotEquals(-1L, storedEntry.getSize()); assertEquals(0L, storedEntry.getDataOffset()%1024); assertNotNull(storedAlignmentEx); assertEquals(1024, storedAlignmentEx.getAlignment()); assertFalse(storedAlignmentEx.allowMethodChange()); try (InputStream stream = zf.getInputStream(storedEntry)) { Assert.assertEquals("Hello Stored\n", new String(IOUtils.toByteArray(stream), Charset.forName("UTF-8"))); } ZipArchiveEntry storedEntry2 = zf.getEntry("stored2.txt"); ResourceAlignmentExtraField stored2AlignmentEx = (ResourceAlignmentExtraField)storedEntry2.getExtraField(ResourceAlignmentExtraField.ID); assertNotEquals(-1L, storedEntry2.getCompressedSize()); assertNotEquals(-1L, storedEntry2.getSize()); assertEquals(0L, storedEntry2.getDataOffset()%1024); assertNotNull(stored2AlignmentEx); assertEquals(1024, stored2AlignmentEx.getAlignment()); assertFalse(stored2AlignmentEx.allowMethodChange()); try (InputStream stream = zf.getInputStream(storedEntry2)) { Assert.assertEquals("Hello overload-alignment Stored\n", new String(IOUtils.toByteArray(stream), Charset.forName("UTF-8"))); } ZipArchiveEntry storedEntry3 = zf.getEntry("stored3.txt"); ResourceAlignmentExtraField stored3AlignmentEx = (ResourceAlignmentExtraField)storedEntry3.getExtraField(ResourceAlignmentExtraField.ID); assertNotEquals(-1L, storedEntry3.getCompressedSize()); assertNotEquals(-1L, storedEntry3.getSize()); assertEquals(0L, storedEntry3.getDataOffset()%1024); assertNotNull(stored3AlignmentEx); assertEquals(1024, stored3AlignmentEx.getAlignment()); assertFalse(stored3AlignmentEx.allowMethodChange()); try (InputStream stream = zf.getInputStream(storedEntry3)) { Assert.assertEquals("Hello copy-alignment Stored\n", new String(IOUtils.toByteArray(stream), Charset.forName("UTF-8"))); } } } /** * Test too big alignment, resulting into exceeding extra field limit. */ @Test(expected = IllegalArgumentException.class) public void testEntryAlignmentExceed() throws Exception { SeekableInMemoryByteChannel zipContent = new SeekableInMemoryByteChannel(); try (ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(zipContent)) { ZipArchiveEntry inflatedEntry = new ZipArchiveEntry("inflated.txt"); inflatedEntry.setMethod(ZipEntry.STORED); inflatedEntry.setAlignment(0x20000); } } /** * Test non power of 2 alignment. */ @Test(expected = IllegalArgumentException.class) public void testInvalidAlignment() throws Exception { ZipArchiveEntry entry = new ZipArchiveEntry("dummy"); entry.setAlignment(3); } @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", ZipArchiveEntry.NameSource.NAME_WITH_EFS_FLAG); } /** * @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); ZipFile zf = new ZipFile(archive)) { byte[] orig = IOUtils.toByteArray(in); ZipArchiveEntry e = zf.getEntry("input2"); try (InputStream s = zf.getInputStream(e)) { byte[] fromZip = IOUtils.toByteArray(s); assertArrayEquals(orig, fromZip); } } } private void assertAllReadMethods(byte[] expected, ZipFile zipFile, ZipArchiveEntry entry) { // simple IOUtil read try (InputStream stream = zf.getInputStream(entry)) { byte[] full = IOUtils.toByteArray(stream); assertArrayEquals(expected, full); } catch (IOException ex) { throw new RuntimeException(ex); } // big buffer at the beginning and then chunks by IOUtils read try (InputStream stream = zf.getInputStream(entry)) { byte[] full; byte[] bytes = new byte[0x40000]; int read = stream.read(bytes); if (read < 0) { full = new byte[0]; } else { full = readStreamRest(bytes, read, stream); } assertArrayEquals(expected, full); } catch (IOException ex) { throw new RuntimeException(ex); } // small chunk / single byte and big buffer then try (InputStream stream = zf.getInputStream(entry)) { byte[] full; int single = stream.read(); if (single < 0) { full = new byte[0]; } else { byte[] big = new byte[0x40000]; big[0] = (byte)single; int read = stream.read(big, 1, big.length-1); if (read < 0) { full = new byte[]{ (byte)single }; } else { full = readStreamRest(big, read+1, stream); } } assertArrayEquals(expected, full); } catch (IOException ex) { throw new RuntimeException(ex); } } /** * Utility to append the rest of the stream to already read data. */ private byte[] readStreamRest(byte[] beginning, int length, InputStream stream) throws IOException { byte[] rest = IOUtils.toByteArray(stream); byte[] full = new byte[length+rest.length]; System.arraycopy(beginning, 0, full, 0, length); System.arraycopy(rest, 0, full, length, rest.length); return full; } private long calculateCrc32(byte[] content) { CRC32 crc = new CRC32(); crc.update(content); return crc.getValue(); } /* * ordertest.zip has been handcrafted. * * It contains enough files so any random coincidence of * entries.keySet() and central directory order would be unlikely * - in fact testCDOrder fails in svn revision 920284. * * The central directory has ZipFile and ZipUtil swapped so * central directory order is different from entry data order. */ private void readOrderTest() throws Exception { final File archive = getFile("ordertest.zip"); zf = new ZipFile(archive); } private static void assertEntryName(final ArrayList<ZipArchiveEntry> entries, final int index, final String expectedName) { final ZipArchiveEntry ze = entries.get(index); assertEquals("src/main/java/org/apache/commons/compress/archivers/zip/" + expectedName + ".java", ze.getName()); } private static void nameSource(String archive, String entry, ZipArchiveEntry.NameSource expected) throws Exception { try (ZipFile zf = new ZipFile(getFile(archive))) { ZipArchiveEntry ze = zf.getEntry(entry); assertEquals(entry, ze.getName()); assertEquals(expected, ze.getNameSource()); } } }
[ { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipFile.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipFile", "be_test_function_name": "access$300", "be_test_function_signature": "(Lorg/apache/commons/compress/archivers/zip/ZipFile;)Ljava/nio/channels/SeekableByteChannel;", "line_numbers": [ "85" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipFile.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipFile", "be_test_function_name": "close", "be_test_function_signature": "()V", "line_numbers": [ "320", "322", "323" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipFile.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipFile", "be_test_function_name": "closeQuietly", "be_test_function_signature": "(Lorg/apache/commons/compress/archivers/zip/ZipFile;)V", "line_numbers": [ "331", "332" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipFile.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipFile", "be_test_function_name": "createBoundedInputStream", "be_test_function_signature": "(JJ)Lorg/apache/commons/compress/archivers/zip/ZipFile$BoundedInputStream;", "line_numbers": [ "1089" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipFile.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipFile", "be_test_function_name": "getEntry", "be_test_function_signature": "(Ljava/lang/String;)Lorg/apache/commons/compress/archivers/zip/ZipArchiveEntry;", "line_numbers": [ "375", "376" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipFile.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipFile", "be_test_function_name": "getInputStream", "be_test_function_signature": "(Lorg/apache/commons/compress/archivers/zip/ZipArchiveEntry;)Ljava/io/InputStream;", "line_numbers": [ "474", "475", "478", "479", "484", "486", "487", "489", "491", "493", "496", "497", "498", "509", "511", "526" ], "method_line_rate": 0.4375 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipFile.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipFile", "be_test_function_name": "populateFromCentralDirectory", "be_test_function_signature": "()Ljava/util/Map;", "line_numbers": [ "610", "613", "615", "616", "617", "619", "620", "624", "625", "626", "627", "628", "630" ], "method_line_rate": 0.9230769230769231 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipFile.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipFile", "be_test_function_name": "positionAtCentralDirectory", "be_test_function_signature": "()V", "line_numbers": [ "875", "876", "877", "879", "880", "881", "882", "883", "886", "888", "889", "891", "893", "895" ], "method_line_rate": 0.9285714285714286 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipFile.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipFile", "be_test_function_name": "positionAtCentralDirectory32", "be_test_function_signature": "()V", "line_numbers": [ "935", "936", "937", "938", "939" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipFile.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipFile", "be_test_function_name": "positionAtEndOfCentralDirectoryRecord", "be_test_function_signature": "()V", "line_numbers": [ "947", "949", "950", "952" ], "method_line_rate": 0.75 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipFile.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipFile", "be_test_function_name": "readCentralDirectoryEntry", "be_test_function_signature": "(Ljava/util/Map;)V", "line_numbers": [ "645", "646", "647", "648", "650", "651", "652", "653", "655", "656", "658", "659", "660", "662", "663", "665", "666", "668", "671", "672", "674", "675", "676", "678", "679", "681", "682", "684", "685", "687", "688", "690", "691", "693", "694", "696", "697", "699", "700", "702", "703", "705", "706", "707", "710", "712", "714", "715", "716", "718", "720", "721", "722", "724", "725", "727" ], "method_line_rate": 0.9821428571428571 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipFile.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipFile", "be_test_function_name": "resolveLocalFileHeaderData", "be_test_function_signature": "(Ljava/util/Map;)V", "line_numbers": [ "1036", "1039", "1040", "1041", "1042", "1043", "1044", "1045", "1046", "1047", "1048", "1049", "1050", "1051", "1052", "1053", "1055", "1057", "1058", "1059", "1063", "1064", "1065", "1066", "1067", "1069", "1070", "1071" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipFile.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipFile", "be_test_function_name": "setSizesAndOffsetFromZip64Extra", "be_test_function_signature": "(Lorg/apache/commons/compress/archivers/zip/ZipArchiveEntry;I)V", "line_numbers": [ "744", "747", "748", "749", "750", "752", "757", "758", "759", "760", "763", "764", "765", "766", "769", "770", "773" ], "method_line_rate": 0.17647058823529413 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipFile.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipFile", "be_test_function_name": "skipBytes", "be_test_function_signature": "(I)V", "line_numbers": [ "1003", "1004", "1005", "1006", "1008", "1009" ], "method_line_rate": 0.8333333333333334 }, { "be_test_class_file": "org/apache/commons/compress/archivers/zip/ZipFile.java", "be_test_class_name": "org.apache.commons.compress.archivers.zip.ZipFile", "be_test_function_name": "tryToLocateSignature", "be_test_function_signature": "(JJ[B)Z", "line_numbers": [ "962", "963", "964", "966", "967", "968", "970", "971", "972", "973", "974", "975", "976", "977", "978", "979", "980", "981", "982", "983", "984", "985", "992", "993", "995" ], "method_line_rate": 0.92 } ]
public class JSTypeTest extends BaseJSTypeTestCase
public void testCreateObjectType() throws Exception { // simple ObjectType subDate = registry.createObjectType(DATE_TYPE.getImplicitPrototype()); assertTypeEquals(DATE_TYPE.getImplicitPrototype(), subDate.getImplicitPrototype()); assertNull(subDate.getReferenceName()); assertEquals("{...}", subDate.toString()); // name, node, prototype ObjectType subError = registry.createObjectType("Foo", null, ERROR_TYPE.getImplicitPrototype()); assertTypeEquals(ERROR_TYPE.getImplicitPrototype(), subError.getImplicitPrototype()); assertEquals("Foo", subError.getReferenceName()); }
// public void testRecordTypeGreatestSubType8(); // public void testApplyOfDateMethod(); // public void testCallOfDateMethod(); // public void testFunctionTypeRepresentation(); // public void testFunctionTypeRelationships(); // public void testProxiedFunctionTypeRelationships(); // public void testFunctionSubTypeRelationships(); // public void testFunctionPrototypeAndImplicitPrototype1(); // public void testFunctionPrototypeAndImplicitPrototype2(); // public void testJSDocOnPrototypeProperty() throws Exception; // public void testVoidType() throws Exception; // public void testBooleanValueType() throws Exception; // public void testBooleanObjectType() throws Exception; // public void testEnumType() throws Exception; // public void testEnumElementType() throws Exception; // public void testStringEnumType() throws Exception; // public void testStringObjectEnumType() throws Exception; // public void testObjectType() throws Exception; // public void testGoogBar() throws Exception; // public void testObjectTypePropertiesCount() throws Exception; // public void testDefineProperties(); // public void testObjectTypePropertiesCountWithShadowing(); // public void testNamedGoogBar() throws Exception; // public void testPrototypeChaining() throws Exception; // public void testInstanceFunctionChaining() throws Exception; // @SuppressWarnings("checked") // public void testCanTestForEqualityWithCornerCases(); // public void testTestForEquality(); // private void compare(TernaryValue r, JSType t1, JSType t2); // private void assertCanTestForEqualityWith(JSType t1, JSType t2); // private void assertCannotTestForEqualityWith(JSType t1, JSType t2); // public void testSubtypingSimpleTypes() throws Exception; // public void testSubtypingObjectTopOfObjects() throws Exception; // public void testSubtypingFunctionPrototypeType() throws Exception; // public void testSubtypingFunctionFixedArgs() throws Exception; // public void testSubtypingFunctionMultipleFixedArgs() throws Exception; // public void testSubtypingFunctionFixedArgsNotMatching() throws Exception; // public void testSubtypingFunctionVariableArgsOneOnly() throws Exception; // public void testSubtypingFunctionVariableArgsBoth() throws Exception; // public void testSubtypingMostGeneralFunction() throws Exception; // private List<JSType> getTypesToTestForSymmetry(); // public void testSymmetryOfTestForEquality(); // public void testSymmetryOfLeastSupertype(); // public void testWeirdBug(); // public void testSymmetryOfGreatestSubtype(); // public void testReflexivityOfLeastSupertype(); // public void testReflexivityOfGreatestSubtype(); // public void testLeastSupertypeUnresolvedNamedType(); // public void testLeastSupertypeUnresolvedNamedType2(); // public void testLeastSupertypeUnresolvedNamedType3(); // public void testSubclassOfUnresolvedNamedType(); // public void testSupertypeOfProxiedFunctionTypes(); // public void testTypeOfThisIsProxied(); // public void testNamedTypeEquals(); // public void testNamedTypeEquals2(); // public void testForwardDeclaredNamedTypeEquals(); // public void testForwardDeclaredNamedType(); // public void testGreatestSubtypeSimpleTypes(); // public void testSubtypingDerivedExtendsNamedBaseType() throws Exception; // public void testNamedSubtypeChain() throws Exception; // public void testRecordSubtypeChain() throws Exception; // public void testRecordAndObjectChain2() throws Exception; // public void testRecordAndObjectChain3() throws Exception; // public void testNullableNamedTypeChain() throws Exception; // public void testEnumTypeChain() throws Exception; // public void testFunctionSubtypeChain() throws Exception; // public void testFunctionUnionSubtypeChain() throws Exception; // public void testConstructorSubtypeChain() throws Exception; // public void testGoogBarSubtypeChain() throws Exception; // public void testConstructorWithArgSubtypeChain() throws Exception; // public void testInterfaceInstanceSubtypeChain() throws Exception; // public void testInterfaceInheritanceSubtypeChain() throws Exception; // public void testAnonymousObjectChain() throws Exception; // public void testAnonymousEnumElementChain() throws Exception; // public void testTemplatizedArrayChain() throws Exception; // public void testTemplatizedArrayChain2() throws Exception; // public void testTemplatizedObjectChain() throws Exception; // public void testMixedTemplatizedTypeChain() throws Exception; // public void testTemplatizedTypeSubtypes(); // public void testTemplatizedTypeRelations() throws Exception; // public void verifySubtypeChain(List<JSType> typeChain) throws Exception; // public void verifySubtypeChain(List<JSType> typeChain, // boolean checkSubtyping) throws Exception; // JSType getNamedWrapper(String name, JSType jstype); // @SuppressWarnings("checked") // public void testRestrictedTypeGivenToBoolean(); // public void testRegisterProperty(); // public void testRegisterPropertyMemoization(); // public void testGreatestSubtypeWithProperty(); // public void testGoodSetPrototypeBasedOn(); // public void testLateSetPrototypeBasedOn(); // public void testGetTypeUnderEquality1(); // public void testGetTypesUnderEquality2(); // public void testGetTypesUnderEquality3(); // @SuppressWarnings("checked") // public void testGetTypesUnderEquality4(); // public void testGetTypesUnderEquality5(); // public void testGetTypesUnderEquality6(); // private void testGetTypeUnderEquality( // JSType t1, JSType t2, JSType t1Eq, JSType t2Eq); // @SuppressWarnings("checked") // public void testGetTypesUnderInequality1(); // @SuppressWarnings("checked") // public void testGetTypesUnderInequality2(); // @SuppressWarnings("checked") // public void testGetTypesUnderInequality3(); // @SuppressWarnings("checked") // public void testGetTypesUnderInequality4() throws Exception; // private void testGetTypesUnderInequality( // JSType t1, JSType t2, JSType t1Eq, JSType t2Eq); // public void testCreateRecordType() throws Exception; // public void testCreateOptionalType() throws Exception; // public void assertUnionContains(UnionType union, JSType type); // public void testCreateAnonymousObjectType() throws Exception; // public void testCreateAnonymousObjectType2() throws Exception; // public void testCreateObjectType() throws Exception; // @SuppressWarnings("checked") // public void testBug903110() throws Exception; // public void testBug904123() throws Exception; // private void assertTypeCanAssignToItself(JSType type); // public void testHasOwnProperty() throws Exception; // public void testNamedTypeHasOwnProperty() throws Exception; // public void testInterfaceHasOwnProperty() throws Exception; // public void testGetPropertyNames() throws Exception; // public void testGetAndSetJSDocInfoWithNamedType() throws Exception; // public void testGetAndSetJSDocInfoWithObjectTypes() throws Exception; // public void testGetAndSetJSDocInfoWithNoType() throws Exception; // public void testObjectGetSubTypes() throws Exception; // public void testImplementingType() throws Exception; // public void testIsTemplatedType() throws Exception; // public void testTemplatizedType() throws Exception; // public void testPartiallyTemplatizedType() throws Exception; // public void testCanCastTo(); // private static boolean containsType( // Iterable<? extends JSType> types, JSType type); // private static boolean assertTypeListEquals( // Iterable<? extends JSType> typeListA, // Iterable<? extends JSType> typeListB); // private ArrowType createArrowType(Node params); // @Override // public StaticSlot<JSType> getSlot(String name); // } // You are a professional Java test case writer, please create a test case named `testCreateObjectType` for the `JSType` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests the factory methods * {@link JSTypeRegistry#createObjectType(ObjectType)}} and * {@link JSTypeRegistry#createObjectType(String, Node, ObjectType)}}. */
test/com/google/javascript/rhino/jstype/JSTypeTest.java
package com.google.javascript.rhino.jstype; import static com.google.javascript.rhino.jstype.TernaryValue.UNKNOWN; import com.google.common.base.Predicate; import com.google.javascript.rhino.ErrorReporter; import com.google.javascript.rhino.JSDocInfo; import java.io.Serializable; import java.util.Comparator;
JSType(JSTypeRegistry registry); JSType(JSTypeRegistry registry, TemplateTypeMap templateTypeMap); JSType getNativeType(JSTypeNative typeId); public JSDocInfo getJSDocInfo(); public String getDisplayName(); public boolean hasDisplayName(); public boolean hasProperty(String pname); public boolean isNoType(); public boolean isNoResolvedType(); public boolean isNoObjectType(); public final boolean isEmptyType(); public boolean isNumberObjectType(); public boolean isNumberValueType(); public boolean isFunctionPrototypeType(); public boolean isStringObjectType(); boolean isTheObjectType(); public boolean isStringValueType(); public final boolean isString(); public final boolean isNumber(); public boolean isArrayType(); public boolean isBooleanObjectType(); public boolean isBooleanValueType(); public boolean isRegexpType(); public boolean isDateType(); public boolean isNullType(); public boolean isVoidType(); public boolean isAllType(); public boolean isUnknownType(); public boolean isCheckedUnknownType(); public final boolean isUnionType(); public boolean isStruct(); public boolean isDict(); public UnionType toMaybeUnionType(); public final boolean isGlobalThisType(); public final boolean isFunctionType(); public FunctionType toMaybeFunctionType(); public static FunctionType toMaybeFunctionType(JSType type); public final boolean isEnumElementType(); public EnumElementType toMaybeEnumElementType(); public boolean isEnumType(); public EnumType toMaybeEnumType(); boolean isNamedType(); public boolean isRecordType(); RecordType toMaybeRecordType(); public final boolean isTemplatizedType(); public TemplatizedType toMaybeTemplatizedType(); public static TemplatizedType toMaybeTemplatizedType(JSType type); public final boolean isTemplateType(); public TemplateType toMaybeTemplateType(); public static TemplateType toMaybeTemplateType(JSType type); public boolean hasAnyTemplateTypes(); boolean hasAnyTemplateTypesInternal(); public TemplateTypeMap getTemplateTypeMap(); public void extendTemplateTypeMap(TemplateTypeMap otherMap); public boolean isObject(); public boolean isConstructor(); public boolean isNominalType(); public final boolean isNominalConstructor(); public boolean isInstanceType(); public boolean isInterface(); public boolean isOrdinaryFunction(); public final boolean isEquivalentTo(JSType that); public final boolean isInvariant(JSType that); public final boolean differsFrom(JSType that); boolean checkEquivalenceHelper( final JSType that, EquivalenceMethod eqMethod); private String getConcreteNominalTypeName(ObjectType objType); public static boolean isEquivalent(JSType typeA, JSType typeB); @Override public boolean equals(Object jsType); @Override public int hashCode(); public final boolean matchesInt32Context(); public final boolean matchesUint32Context(); public boolean matchesNumberContext(); public boolean matchesStringContext(); public boolean matchesObjectContext(); public JSType findPropertyType(String propertyName); public boolean canBeCalled(); public boolean canCastTo(JSType that); public JSType autoboxesTo(); public JSType unboxesTo(); public ObjectType toObjectType(); public JSType autobox(); public final ObjectType dereference(); public final boolean canTestForEqualityWith(JSType that); public TernaryValue testForEquality(JSType that); TernaryValue testForEqualityHelper(JSType aType, JSType bType); public final boolean canTestForShallowEqualityWith(JSType that); public boolean isNullable(); public JSType collapseUnion(); public JSType getLeastSupertype(JSType that); static JSType getLeastSupertype(JSType thisType, JSType thatType); public JSType getGreatestSubtype(JSType that); static JSType getGreatestSubtype(JSType thisType, JSType thatType); static JSType filterNoResolvedType(JSType type); public JSType getRestrictedTypeGivenToBooleanOutcome(boolean outcome); public abstract BooleanLiteralSet getPossibleToBooleanOutcomes(); public TypePair getTypesUnderEquality(JSType that); public TypePair getTypesUnderInequality(JSType that); public TypePair getTypesUnderShallowEquality(JSType that); public TypePair getTypesUnderShallowInequality(JSType that); public JSType restrictByNotNullOrUndefined(); public boolean isSubtype(JSType that); static boolean isSubtypeHelper(JSType thisType, JSType thatType); static boolean isExemptFromTemplateTypeInvariance(JSType type); public abstract <T> T visit(Visitor<T> visitor); abstract <T> T visit(RelationshipVisitor<T> visitor, JSType that); public final JSType resolve(ErrorReporter t, StaticScope<JSType> scope); abstract JSType resolveInternal(ErrorReporter t, StaticScope<JSType> scope); void setResolvedTypeInternal(JSType type); public final boolean isResolved(); public final void clearResolved(); static final JSType safeResolve( JSType type, ErrorReporter t, StaticScope<JSType> scope); public boolean setValidator(Predicate<JSType> validator); @Override public String toString(); public String toDebugHashCodeString(); public final String toAnnotationString(); abstract String toStringHelper(boolean forAnnotations); public void matchConstraint(JSType constraint); public TypePair(JSType typeA, JSType typeB); @Override public int compare(JSType t1, JSType t2);
5,891
testCreateObjectType
```java public void testRecordTypeGreatestSubType8(); public void testApplyOfDateMethod(); public void testCallOfDateMethod(); public void testFunctionTypeRepresentation(); public void testFunctionTypeRelationships(); public void testProxiedFunctionTypeRelationships(); public void testFunctionSubTypeRelationships(); public void testFunctionPrototypeAndImplicitPrototype1(); public void testFunctionPrototypeAndImplicitPrototype2(); public void testJSDocOnPrototypeProperty() throws Exception; public void testVoidType() throws Exception; public void testBooleanValueType() throws Exception; public void testBooleanObjectType() throws Exception; public void testEnumType() throws Exception; public void testEnumElementType() throws Exception; public void testStringEnumType() throws Exception; public void testStringObjectEnumType() throws Exception; public void testObjectType() throws Exception; public void testGoogBar() throws Exception; public void testObjectTypePropertiesCount() throws Exception; public void testDefineProperties(); public void testObjectTypePropertiesCountWithShadowing(); public void testNamedGoogBar() throws Exception; public void testPrototypeChaining() throws Exception; public void testInstanceFunctionChaining() throws Exception; @SuppressWarnings("checked") public void testCanTestForEqualityWithCornerCases(); public void testTestForEquality(); private void compare(TernaryValue r, JSType t1, JSType t2); private void assertCanTestForEqualityWith(JSType t1, JSType t2); private void assertCannotTestForEqualityWith(JSType t1, JSType t2); public void testSubtypingSimpleTypes() throws Exception; public void testSubtypingObjectTopOfObjects() throws Exception; public void testSubtypingFunctionPrototypeType() throws Exception; public void testSubtypingFunctionFixedArgs() throws Exception; public void testSubtypingFunctionMultipleFixedArgs() throws Exception; public void testSubtypingFunctionFixedArgsNotMatching() throws Exception; public void testSubtypingFunctionVariableArgsOneOnly() throws Exception; public void testSubtypingFunctionVariableArgsBoth() throws Exception; public void testSubtypingMostGeneralFunction() throws Exception; private List<JSType> getTypesToTestForSymmetry(); public void testSymmetryOfTestForEquality(); public void testSymmetryOfLeastSupertype(); public void testWeirdBug(); public void testSymmetryOfGreatestSubtype(); public void testReflexivityOfLeastSupertype(); public void testReflexivityOfGreatestSubtype(); public void testLeastSupertypeUnresolvedNamedType(); public void testLeastSupertypeUnresolvedNamedType2(); public void testLeastSupertypeUnresolvedNamedType3(); public void testSubclassOfUnresolvedNamedType(); public void testSupertypeOfProxiedFunctionTypes(); public void testTypeOfThisIsProxied(); public void testNamedTypeEquals(); public void testNamedTypeEquals2(); public void testForwardDeclaredNamedTypeEquals(); public void testForwardDeclaredNamedType(); public void testGreatestSubtypeSimpleTypes(); public void testSubtypingDerivedExtendsNamedBaseType() throws Exception; public void testNamedSubtypeChain() throws Exception; public void testRecordSubtypeChain() throws Exception; public void testRecordAndObjectChain2() throws Exception; public void testRecordAndObjectChain3() throws Exception; public void testNullableNamedTypeChain() throws Exception; public void testEnumTypeChain() throws Exception; public void testFunctionSubtypeChain() throws Exception; public void testFunctionUnionSubtypeChain() throws Exception; public void testConstructorSubtypeChain() throws Exception; public void testGoogBarSubtypeChain() throws Exception; public void testConstructorWithArgSubtypeChain() throws Exception; public void testInterfaceInstanceSubtypeChain() throws Exception; public void testInterfaceInheritanceSubtypeChain() throws Exception; public void testAnonymousObjectChain() throws Exception; public void testAnonymousEnumElementChain() throws Exception; public void testTemplatizedArrayChain() throws Exception; public void testTemplatizedArrayChain2() throws Exception; public void testTemplatizedObjectChain() throws Exception; public void testMixedTemplatizedTypeChain() throws Exception; public void testTemplatizedTypeSubtypes(); public void testTemplatizedTypeRelations() throws Exception; public void verifySubtypeChain(List<JSType> typeChain) throws Exception; public void verifySubtypeChain(List<JSType> typeChain, boolean checkSubtyping) throws Exception; JSType getNamedWrapper(String name, JSType jstype); @SuppressWarnings("checked") public void testRestrictedTypeGivenToBoolean(); public void testRegisterProperty(); public void testRegisterPropertyMemoization(); public void testGreatestSubtypeWithProperty(); public void testGoodSetPrototypeBasedOn(); public void testLateSetPrototypeBasedOn(); public void testGetTypeUnderEquality1(); public void testGetTypesUnderEquality2(); public void testGetTypesUnderEquality3(); @SuppressWarnings("checked") public void testGetTypesUnderEquality4(); public void testGetTypesUnderEquality5(); public void testGetTypesUnderEquality6(); private void testGetTypeUnderEquality( JSType t1, JSType t2, JSType t1Eq, JSType t2Eq); @SuppressWarnings("checked") public void testGetTypesUnderInequality1(); @SuppressWarnings("checked") public void testGetTypesUnderInequality2(); @SuppressWarnings("checked") public void testGetTypesUnderInequality3(); @SuppressWarnings("checked") public void testGetTypesUnderInequality4() throws Exception; private void testGetTypesUnderInequality( JSType t1, JSType t2, JSType t1Eq, JSType t2Eq); public void testCreateRecordType() throws Exception; public void testCreateOptionalType() throws Exception; public void assertUnionContains(UnionType union, JSType type); public void testCreateAnonymousObjectType() throws Exception; public void testCreateAnonymousObjectType2() throws Exception; public void testCreateObjectType() throws Exception; @SuppressWarnings("checked") public void testBug903110() throws Exception; public void testBug904123() throws Exception; private void assertTypeCanAssignToItself(JSType type); public void testHasOwnProperty() throws Exception; public void testNamedTypeHasOwnProperty() throws Exception; public void testInterfaceHasOwnProperty() throws Exception; public void testGetPropertyNames() throws Exception; public void testGetAndSetJSDocInfoWithNamedType() throws Exception; public void testGetAndSetJSDocInfoWithObjectTypes() throws Exception; public void testGetAndSetJSDocInfoWithNoType() throws Exception; public void testObjectGetSubTypes() throws Exception; public void testImplementingType() throws Exception; public void testIsTemplatedType() throws Exception; public void testTemplatizedType() throws Exception; public void testPartiallyTemplatizedType() throws Exception; public void testCanCastTo(); private static boolean containsType( Iterable<? extends JSType> types, JSType type); private static boolean assertTypeListEquals( Iterable<? extends JSType> typeListA, Iterable<? extends JSType> typeListB); private ArrowType createArrowType(Node params); @Override public StaticSlot<JSType> getSlot(String name); } ``` You are a professional Java test case writer, please create a test case named `testCreateObjectType` for the `JSType` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests the factory methods * {@link JSTypeRegistry#createObjectType(ObjectType)}} and * {@link JSTypeRegistry#createObjectType(String, Node, ObjectType)}}. */
5,876
// public void testRecordTypeGreatestSubType8(); // public void testApplyOfDateMethod(); // public void testCallOfDateMethod(); // public void testFunctionTypeRepresentation(); // public void testFunctionTypeRelationships(); // public void testProxiedFunctionTypeRelationships(); // public void testFunctionSubTypeRelationships(); // public void testFunctionPrototypeAndImplicitPrototype1(); // public void testFunctionPrototypeAndImplicitPrototype2(); // public void testJSDocOnPrototypeProperty() throws Exception; // public void testVoidType() throws Exception; // public void testBooleanValueType() throws Exception; // public void testBooleanObjectType() throws Exception; // public void testEnumType() throws Exception; // public void testEnumElementType() throws Exception; // public void testStringEnumType() throws Exception; // public void testStringObjectEnumType() throws Exception; // public void testObjectType() throws Exception; // public void testGoogBar() throws Exception; // public void testObjectTypePropertiesCount() throws Exception; // public void testDefineProperties(); // public void testObjectTypePropertiesCountWithShadowing(); // public void testNamedGoogBar() throws Exception; // public void testPrototypeChaining() throws Exception; // public void testInstanceFunctionChaining() throws Exception; // @SuppressWarnings("checked") // public void testCanTestForEqualityWithCornerCases(); // public void testTestForEquality(); // private void compare(TernaryValue r, JSType t1, JSType t2); // private void assertCanTestForEqualityWith(JSType t1, JSType t2); // private void assertCannotTestForEqualityWith(JSType t1, JSType t2); // public void testSubtypingSimpleTypes() throws Exception; // public void testSubtypingObjectTopOfObjects() throws Exception; // public void testSubtypingFunctionPrototypeType() throws Exception; // public void testSubtypingFunctionFixedArgs() throws Exception; // public void testSubtypingFunctionMultipleFixedArgs() throws Exception; // public void testSubtypingFunctionFixedArgsNotMatching() throws Exception; // public void testSubtypingFunctionVariableArgsOneOnly() throws Exception; // public void testSubtypingFunctionVariableArgsBoth() throws Exception; // public void testSubtypingMostGeneralFunction() throws Exception; // private List<JSType> getTypesToTestForSymmetry(); // public void testSymmetryOfTestForEquality(); // public void testSymmetryOfLeastSupertype(); // public void testWeirdBug(); // public void testSymmetryOfGreatestSubtype(); // public void testReflexivityOfLeastSupertype(); // public void testReflexivityOfGreatestSubtype(); // public void testLeastSupertypeUnresolvedNamedType(); // public void testLeastSupertypeUnresolvedNamedType2(); // public void testLeastSupertypeUnresolvedNamedType3(); // public void testSubclassOfUnresolvedNamedType(); // public void testSupertypeOfProxiedFunctionTypes(); // public void testTypeOfThisIsProxied(); // public void testNamedTypeEquals(); // public void testNamedTypeEquals2(); // public void testForwardDeclaredNamedTypeEquals(); // public void testForwardDeclaredNamedType(); // public void testGreatestSubtypeSimpleTypes(); // public void testSubtypingDerivedExtendsNamedBaseType() throws Exception; // public void testNamedSubtypeChain() throws Exception; // public void testRecordSubtypeChain() throws Exception; // public void testRecordAndObjectChain2() throws Exception; // public void testRecordAndObjectChain3() throws Exception; // public void testNullableNamedTypeChain() throws Exception; // public void testEnumTypeChain() throws Exception; // public void testFunctionSubtypeChain() throws Exception; // public void testFunctionUnionSubtypeChain() throws Exception; // public void testConstructorSubtypeChain() throws Exception; // public void testGoogBarSubtypeChain() throws Exception; // public void testConstructorWithArgSubtypeChain() throws Exception; // public void testInterfaceInstanceSubtypeChain() throws Exception; // public void testInterfaceInheritanceSubtypeChain() throws Exception; // public void testAnonymousObjectChain() throws Exception; // public void testAnonymousEnumElementChain() throws Exception; // public void testTemplatizedArrayChain() throws Exception; // public void testTemplatizedArrayChain2() throws Exception; // public void testTemplatizedObjectChain() throws Exception; // public void testMixedTemplatizedTypeChain() throws Exception; // public void testTemplatizedTypeSubtypes(); // public void testTemplatizedTypeRelations() throws Exception; // public void verifySubtypeChain(List<JSType> typeChain) throws Exception; // public void verifySubtypeChain(List<JSType> typeChain, // boolean checkSubtyping) throws Exception; // JSType getNamedWrapper(String name, JSType jstype); // @SuppressWarnings("checked") // public void testRestrictedTypeGivenToBoolean(); // public void testRegisterProperty(); // public void testRegisterPropertyMemoization(); // public void testGreatestSubtypeWithProperty(); // public void testGoodSetPrototypeBasedOn(); // public void testLateSetPrototypeBasedOn(); // public void testGetTypeUnderEquality1(); // public void testGetTypesUnderEquality2(); // public void testGetTypesUnderEquality3(); // @SuppressWarnings("checked") // public void testGetTypesUnderEquality4(); // public void testGetTypesUnderEquality5(); // public void testGetTypesUnderEquality6(); // private void testGetTypeUnderEquality( // JSType t1, JSType t2, JSType t1Eq, JSType t2Eq); // @SuppressWarnings("checked") // public void testGetTypesUnderInequality1(); // @SuppressWarnings("checked") // public void testGetTypesUnderInequality2(); // @SuppressWarnings("checked") // public void testGetTypesUnderInequality3(); // @SuppressWarnings("checked") // public void testGetTypesUnderInequality4() throws Exception; // private void testGetTypesUnderInequality( // JSType t1, JSType t2, JSType t1Eq, JSType t2Eq); // public void testCreateRecordType() throws Exception; // public void testCreateOptionalType() throws Exception; // public void assertUnionContains(UnionType union, JSType type); // public void testCreateAnonymousObjectType() throws Exception; // public void testCreateAnonymousObjectType2() throws Exception; // public void testCreateObjectType() throws Exception; // @SuppressWarnings("checked") // public void testBug903110() throws Exception; // public void testBug904123() throws Exception; // private void assertTypeCanAssignToItself(JSType type); // public void testHasOwnProperty() throws Exception; // public void testNamedTypeHasOwnProperty() throws Exception; // public void testInterfaceHasOwnProperty() throws Exception; // public void testGetPropertyNames() throws Exception; // public void testGetAndSetJSDocInfoWithNamedType() throws Exception; // public void testGetAndSetJSDocInfoWithObjectTypes() throws Exception; // public void testGetAndSetJSDocInfoWithNoType() throws Exception; // public void testObjectGetSubTypes() throws Exception; // public void testImplementingType() throws Exception; // public void testIsTemplatedType() throws Exception; // public void testTemplatizedType() throws Exception; // public void testPartiallyTemplatizedType() throws Exception; // public void testCanCastTo(); // private static boolean containsType( // Iterable<? extends JSType> types, JSType type); // private static boolean assertTypeListEquals( // Iterable<? extends JSType> typeListA, // Iterable<? extends JSType> typeListB); // private ArrowType createArrowType(Node params); // @Override // public StaticSlot<JSType> getSlot(String name); // } // You are a professional Java test case writer, please create a test case named `testCreateObjectType` for the `JSType` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests the factory methods * {@link JSTypeRegistry#createObjectType(ObjectType)}} and * {@link JSTypeRegistry#createObjectType(String, Node, ObjectType)}}. */ public void testCreateObjectType() throws Exception {
/** * Tests the factory methods * {@link JSTypeRegistry#createObjectType(ObjectType)}} and * {@link JSTypeRegistry#createObjectType(String, Node, ObjectType)}}. */
107
com.google.javascript.rhino.jstype.JSType
test
```java public void testRecordTypeGreatestSubType8(); public void testApplyOfDateMethod(); public void testCallOfDateMethod(); public void testFunctionTypeRepresentation(); public void testFunctionTypeRelationships(); public void testProxiedFunctionTypeRelationships(); public void testFunctionSubTypeRelationships(); public void testFunctionPrototypeAndImplicitPrototype1(); public void testFunctionPrototypeAndImplicitPrototype2(); public void testJSDocOnPrototypeProperty() throws Exception; public void testVoidType() throws Exception; public void testBooleanValueType() throws Exception; public void testBooleanObjectType() throws Exception; public void testEnumType() throws Exception; public void testEnumElementType() throws Exception; public void testStringEnumType() throws Exception; public void testStringObjectEnumType() throws Exception; public void testObjectType() throws Exception; public void testGoogBar() throws Exception; public void testObjectTypePropertiesCount() throws Exception; public void testDefineProperties(); public void testObjectTypePropertiesCountWithShadowing(); public void testNamedGoogBar() throws Exception; public void testPrototypeChaining() throws Exception; public void testInstanceFunctionChaining() throws Exception; @SuppressWarnings("checked") public void testCanTestForEqualityWithCornerCases(); public void testTestForEquality(); private void compare(TernaryValue r, JSType t1, JSType t2); private void assertCanTestForEqualityWith(JSType t1, JSType t2); private void assertCannotTestForEqualityWith(JSType t1, JSType t2); public void testSubtypingSimpleTypes() throws Exception; public void testSubtypingObjectTopOfObjects() throws Exception; public void testSubtypingFunctionPrototypeType() throws Exception; public void testSubtypingFunctionFixedArgs() throws Exception; public void testSubtypingFunctionMultipleFixedArgs() throws Exception; public void testSubtypingFunctionFixedArgsNotMatching() throws Exception; public void testSubtypingFunctionVariableArgsOneOnly() throws Exception; public void testSubtypingFunctionVariableArgsBoth() throws Exception; public void testSubtypingMostGeneralFunction() throws Exception; private List<JSType> getTypesToTestForSymmetry(); public void testSymmetryOfTestForEquality(); public void testSymmetryOfLeastSupertype(); public void testWeirdBug(); public void testSymmetryOfGreatestSubtype(); public void testReflexivityOfLeastSupertype(); public void testReflexivityOfGreatestSubtype(); public void testLeastSupertypeUnresolvedNamedType(); public void testLeastSupertypeUnresolvedNamedType2(); public void testLeastSupertypeUnresolvedNamedType3(); public void testSubclassOfUnresolvedNamedType(); public void testSupertypeOfProxiedFunctionTypes(); public void testTypeOfThisIsProxied(); public void testNamedTypeEquals(); public void testNamedTypeEquals2(); public void testForwardDeclaredNamedTypeEquals(); public void testForwardDeclaredNamedType(); public void testGreatestSubtypeSimpleTypes(); public void testSubtypingDerivedExtendsNamedBaseType() throws Exception; public void testNamedSubtypeChain() throws Exception; public void testRecordSubtypeChain() throws Exception; public void testRecordAndObjectChain2() throws Exception; public void testRecordAndObjectChain3() throws Exception; public void testNullableNamedTypeChain() throws Exception; public void testEnumTypeChain() throws Exception; public void testFunctionSubtypeChain() throws Exception; public void testFunctionUnionSubtypeChain() throws Exception; public void testConstructorSubtypeChain() throws Exception; public void testGoogBarSubtypeChain() throws Exception; public void testConstructorWithArgSubtypeChain() throws Exception; public void testInterfaceInstanceSubtypeChain() throws Exception; public void testInterfaceInheritanceSubtypeChain() throws Exception; public void testAnonymousObjectChain() throws Exception; public void testAnonymousEnumElementChain() throws Exception; public void testTemplatizedArrayChain() throws Exception; public void testTemplatizedArrayChain2() throws Exception; public void testTemplatizedObjectChain() throws Exception; public void testMixedTemplatizedTypeChain() throws Exception; public void testTemplatizedTypeSubtypes(); public void testTemplatizedTypeRelations() throws Exception; public void verifySubtypeChain(List<JSType> typeChain) throws Exception; public void verifySubtypeChain(List<JSType> typeChain, boolean checkSubtyping) throws Exception; JSType getNamedWrapper(String name, JSType jstype); @SuppressWarnings("checked") public void testRestrictedTypeGivenToBoolean(); public void testRegisterProperty(); public void testRegisterPropertyMemoization(); public void testGreatestSubtypeWithProperty(); public void testGoodSetPrototypeBasedOn(); public void testLateSetPrototypeBasedOn(); public void testGetTypeUnderEquality1(); public void testGetTypesUnderEquality2(); public void testGetTypesUnderEquality3(); @SuppressWarnings("checked") public void testGetTypesUnderEquality4(); public void testGetTypesUnderEquality5(); public void testGetTypesUnderEquality6(); private void testGetTypeUnderEquality( JSType t1, JSType t2, JSType t1Eq, JSType t2Eq); @SuppressWarnings("checked") public void testGetTypesUnderInequality1(); @SuppressWarnings("checked") public void testGetTypesUnderInequality2(); @SuppressWarnings("checked") public void testGetTypesUnderInequality3(); @SuppressWarnings("checked") public void testGetTypesUnderInequality4() throws Exception; private void testGetTypesUnderInequality( JSType t1, JSType t2, JSType t1Eq, JSType t2Eq); public void testCreateRecordType() throws Exception; public void testCreateOptionalType() throws Exception; public void assertUnionContains(UnionType union, JSType type); public void testCreateAnonymousObjectType() throws Exception; public void testCreateAnonymousObjectType2() throws Exception; public void testCreateObjectType() throws Exception; @SuppressWarnings("checked") public void testBug903110() throws Exception; public void testBug904123() throws Exception; private void assertTypeCanAssignToItself(JSType type); public void testHasOwnProperty() throws Exception; public void testNamedTypeHasOwnProperty() throws Exception; public void testInterfaceHasOwnProperty() throws Exception; public void testGetPropertyNames() throws Exception; public void testGetAndSetJSDocInfoWithNamedType() throws Exception; public void testGetAndSetJSDocInfoWithObjectTypes() throws Exception; public void testGetAndSetJSDocInfoWithNoType() throws Exception; public void testObjectGetSubTypes() throws Exception; public void testImplementingType() throws Exception; public void testIsTemplatedType() throws Exception; public void testTemplatizedType() throws Exception; public void testPartiallyTemplatizedType() throws Exception; public void testCanCastTo(); private static boolean containsType( Iterable<? extends JSType> types, JSType type); private static boolean assertTypeListEquals( Iterable<? extends JSType> typeListA, Iterable<? extends JSType> typeListB); private ArrowType createArrowType(Node params); @Override public StaticSlot<JSType> getSlot(String name); } ``` You are a professional Java test case writer, please create a test case named `testCreateObjectType` for the `JSType` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests the factory methods * {@link JSTypeRegistry#createObjectType(ObjectType)}} and * {@link JSTypeRegistry#createObjectType(String, Node, ObjectType)}}. */ public void testCreateObjectType() throws Exception { ```
public abstract class JSType implements Serializable
package com.google.javascript.rhino.jstype; import static com.google.javascript.rhino.jstype.TernaryValue.FALSE; import static com.google.javascript.rhino.jstype.TernaryValue.TRUE; import static com.google.javascript.rhino.jstype.TernaryValue.UNKNOWN; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.JSDocInfo.Visibility; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.SimpleErrorReporter; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.JSType.TypePair; import com.google.javascript.rhino.jstype.RecordTypeBuilder.RecordProperty; import com.google.javascript.rhino.testing.AbstractStaticScope; import com.google.javascript.rhino.testing.Asserts; import com.google.javascript.rhino.testing.BaseJSTypeTestCase; import com.google.javascript.rhino.testing.MapBasedScope; import java.util.HashMap; import java.util.List; import java.util.Map;
@Override protected void setUp() throws Exception; public void testUniversalConstructorType() throws Exception; public void testNoObjectType() throws Exception; public void testNoType() throws Exception; public void testNoResolvedType() throws Exception; public void testArrayType() throws Exception; public void testUnknownType() throws Exception; public void testCheckedUnknownType() throws Exception; public void testAllType() throws Exception; public void testTheObjectType() throws Exception; public void testNumberObjectType() throws Exception; public void testNumberValueType() throws Exception; public void testNullType() throws Exception; public void testDateType() throws Exception; public void testRegExpType() throws Exception; public void testStringObjectType() throws Exception; public void testStringValueType() throws Exception; private void assertPropertyTypeDeclared(ObjectType ownerType, String prop); private void assertPropertyTypeInferred(ObjectType ownerType, String prop); private void assertPropertyTypeUnknown(ObjectType ownerType, String prop); private void assertReturnTypeEquals(JSType expectedReturnType, JSType function); public void testRecordType() throws Exception; public void testFunctionInstanceType() throws Exception; public void testFunctionType() throws Exception; public void testRecordTypeSubtyping(); public void testRecordTypeSubtypingWithInferredProperties(); public void testRecordTypeLeastSuperType1(); public void testRecordTypeLeastSuperType2(); public void testRecordTypeLeastSuperType3(); public void testRecordTypeLeastSuperType4(); public void testRecordTypeGreatestSubType1(); public void testRecordTypeGreatestSubType2(); public void testRecordTypeGreatestSubType3(); public void testRecordTypeGreatestSubType4(); public void testRecordTypeGreatestSubType5(); public void testRecordTypeGreatestSubType6(); public void testRecordTypeGreatestSubType7(); public void testRecordTypeGreatestSubType8(); public void testApplyOfDateMethod(); public void testCallOfDateMethod(); public void testFunctionTypeRepresentation(); public void testFunctionTypeRelationships(); public void testProxiedFunctionTypeRelationships(); public void testFunctionSubTypeRelationships(); public void testFunctionPrototypeAndImplicitPrototype1(); public void testFunctionPrototypeAndImplicitPrototype2(); public void testJSDocOnPrototypeProperty() throws Exception; public void testVoidType() throws Exception; public void testBooleanValueType() throws Exception; public void testBooleanObjectType() throws Exception; public void testEnumType() throws Exception; public void testEnumElementType() throws Exception; public void testStringEnumType() throws Exception; public void testStringObjectEnumType() throws Exception; public void testObjectType() throws Exception; public void testGoogBar() throws Exception; public void testObjectTypePropertiesCount() throws Exception; public void testDefineProperties(); public void testObjectTypePropertiesCountWithShadowing(); public void testNamedGoogBar() throws Exception; public void testPrototypeChaining() throws Exception; public void testInstanceFunctionChaining() throws Exception; @SuppressWarnings("checked") public void testCanTestForEqualityWithCornerCases(); public void testTestForEquality(); private void compare(TernaryValue r, JSType t1, JSType t2); private void assertCanTestForEqualityWith(JSType t1, JSType t2); private void assertCannotTestForEqualityWith(JSType t1, JSType t2); public void testSubtypingSimpleTypes() throws Exception; public void testSubtypingObjectTopOfObjects() throws Exception; public void testSubtypingFunctionPrototypeType() throws Exception; public void testSubtypingFunctionFixedArgs() throws Exception; public void testSubtypingFunctionMultipleFixedArgs() throws Exception; public void testSubtypingFunctionFixedArgsNotMatching() throws Exception; public void testSubtypingFunctionVariableArgsOneOnly() throws Exception; public void testSubtypingFunctionVariableArgsBoth() throws Exception; public void testSubtypingMostGeneralFunction() throws Exception; private List<JSType> getTypesToTestForSymmetry(); public void testSymmetryOfTestForEquality(); public void testSymmetryOfLeastSupertype(); public void testWeirdBug(); public void testSymmetryOfGreatestSubtype(); public void testReflexivityOfLeastSupertype(); public void testReflexivityOfGreatestSubtype(); public void testLeastSupertypeUnresolvedNamedType(); public void testLeastSupertypeUnresolvedNamedType2(); public void testLeastSupertypeUnresolvedNamedType3(); public void testSubclassOfUnresolvedNamedType(); public void testSupertypeOfProxiedFunctionTypes(); public void testTypeOfThisIsProxied(); public void testNamedTypeEquals(); public void testNamedTypeEquals2(); public void testForwardDeclaredNamedTypeEquals(); public void testForwardDeclaredNamedType(); public void testGreatestSubtypeSimpleTypes(); public void testSubtypingDerivedExtendsNamedBaseType() throws Exception; public void testNamedSubtypeChain() throws Exception; public void testRecordSubtypeChain() throws Exception; public void testRecordAndObjectChain2() throws Exception; public void testRecordAndObjectChain3() throws Exception; public void testNullableNamedTypeChain() throws Exception; public void testEnumTypeChain() throws Exception; public void testFunctionSubtypeChain() throws Exception; public void testFunctionUnionSubtypeChain() throws Exception; public void testConstructorSubtypeChain() throws Exception; public void testGoogBarSubtypeChain() throws Exception; public void testConstructorWithArgSubtypeChain() throws Exception; public void testInterfaceInstanceSubtypeChain() throws Exception; public void testInterfaceInheritanceSubtypeChain() throws Exception; public void testAnonymousObjectChain() throws Exception; public void testAnonymousEnumElementChain() throws Exception; public void testTemplatizedArrayChain() throws Exception; public void testTemplatizedArrayChain2() throws Exception; public void testTemplatizedObjectChain() throws Exception; public void testMixedTemplatizedTypeChain() throws Exception; public void testTemplatizedTypeSubtypes(); public void testTemplatizedTypeRelations() throws Exception; public void verifySubtypeChain(List<JSType> typeChain) throws Exception; public void verifySubtypeChain(List<JSType> typeChain, boolean checkSubtyping) throws Exception; JSType getNamedWrapper(String name, JSType jstype); @SuppressWarnings("checked") public void testRestrictedTypeGivenToBoolean(); public void testRegisterProperty(); public void testRegisterPropertyMemoization(); public void testGreatestSubtypeWithProperty(); public void testGoodSetPrototypeBasedOn(); public void testLateSetPrototypeBasedOn(); public void testGetTypeUnderEquality1(); public void testGetTypesUnderEquality2(); public void testGetTypesUnderEquality3(); @SuppressWarnings("checked") public void testGetTypesUnderEquality4(); public void testGetTypesUnderEquality5(); public void testGetTypesUnderEquality6(); private void testGetTypeUnderEquality( JSType t1, JSType t2, JSType t1Eq, JSType t2Eq); @SuppressWarnings("checked") public void testGetTypesUnderInequality1(); @SuppressWarnings("checked") public void testGetTypesUnderInequality2(); @SuppressWarnings("checked") public void testGetTypesUnderInequality3(); @SuppressWarnings("checked") public void testGetTypesUnderInequality4() throws Exception; private void testGetTypesUnderInequality( JSType t1, JSType t2, JSType t1Eq, JSType t2Eq); public void testCreateRecordType() throws Exception; public void testCreateOptionalType() throws Exception; public void assertUnionContains(UnionType union, JSType type); public void testCreateAnonymousObjectType() throws Exception; public void testCreateAnonymousObjectType2() throws Exception; public void testCreateObjectType() throws Exception; @SuppressWarnings("checked") public void testBug903110() throws Exception; public void testBug904123() throws Exception; private void assertTypeCanAssignToItself(JSType type); public void testHasOwnProperty() throws Exception; public void testNamedTypeHasOwnProperty() throws Exception; public void testInterfaceHasOwnProperty() throws Exception; public void testGetPropertyNames() throws Exception; public void testGetAndSetJSDocInfoWithNamedType() throws Exception; public void testGetAndSetJSDocInfoWithObjectTypes() throws Exception; public void testGetAndSetJSDocInfoWithNoType() throws Exception; public void testObjectGetSubTypes() throws Exception; public void testImplementingType() throws Exception; public void testIsTemplatedType() throws Exception; public void testTemplatizedType() throws Exception; public void testPartiallyTemplatizedType() throws Exception; public void testCanCastTo(); private static boolean containsType( Iterable<? extends JSType> types, JSType type); private static boolean assertTypeListEquals( Iterable<? extends JSType> typeListA, Iterable<? extends JSType> typeListB); private ArrowType createArrowType(Node params); @Override public StaticSlot<JSType> getSlot(String name);
9d328c05ab6a9fef88d673b6820f76da94fb8130c2b057ca141dfa10f3aa11a3
[ "com.google.javascript.rhino.jstype.JSTypeTest::testCreateObjectType" ]
private static final long serialVersionUID = 1L; private boolean resolved = false; private JSType resolveResult = null; protected TemplateTypeMap templateTypeMap; private boolean inTemplatedCheckVisit = false; private static final CanCastToVisitor CAN_CAST_TO_VISITOR = new CanCastToVisitor(); public static final String UNKNOWN_NAME = "Unknown class name"; public static final String NOT_A_CLASS = "Not declared as a constructor"; public static final String NOT_A_TYPE = "Not declared as a type name"; public static final String EMPTY_TYPE_COMPONENT = "Named type with empty name component"; static final Comparator<JSType> ALPHA = new Comparator<JSType>() { @Override public int compare(JSType t1, JSType t2) { return t1.toString().compareTo(t2.toString()); } }; public static final int ENUMDECL = 1; public static final int NOT_ENUMDECL = 0; final JSTypeRegistry registry;
public void testCreateObjectType() throws Exception
private FunctionType dateMethod; private FunctionType functionType; private NamedType unresolvedNamedType; private FunctionType googBar; private FunctionType googSubBar; private FunctionType googSubSubBar; private ObjectType googBarInst; private ObjectType googSubBarInst; private ObjectType googSubSubBarInst; private NamedType namedGoogBar; private ObjectType subclassOfUnresolvedNamedType; private FunctionType subclassCtor; private FunctionType interfaceType; private ObjectType interfaceInstType; private FunctionType subInterfaceType; private ObjectType subInterfaceInstType; private JSType recordType; private EnumType enumType; private EnumElementType elementsType; private NamedType forwardDeclaredNamedType; private static final StaticScope<JSType> EMPTY_SCOPE = MapBasedScope.emptyScope(); private List<JSType> types;
Closure
/* * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Nick Santos * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package com.google.javascript.rhino.jstype; import static com.google.javascript.rhino.jstype.TernaryValue.FALSE; import static com.google.javascript.rhino.jstype.TernaryValue.TRUE; import static com.google.javascript.rhino.jstype.TernaryValue.UNKNOWN; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.JSDocInfo.Visibility; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.SimpleErrorReporter; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.JSType.TypePair; import com.google.javascript.rhino.jstype.RecordTypeBuilder.RecordProperty; import com.google.javascript.rhino.testing.AbstractStaticScope; import com.google.javascript.rhino.testing.Asserts; import com.google.javascript.rhino.testing.BaseJSTypeTestCase; import com.google.javascript.rhino.testing.MapBasedScope; import java.util.HashMap; import java.util.List; import java.util.Map; // TODO(nicksantos): Split some of this up into per-class unit tests. public class JSTypeTest extends BaseJSTypeTestCase { private FunctionType dateMethod; private FunctionType functionType; private NamedType unresolvedNamedType; private FunctionType googBar; private FunctionType googSubBar; private FunctionType googSubSubBar; private ObjectType googBarInst; private ObjectType googSubBarInst; private ObjectType googSubSubBarInst; private NamedType namedGoogBar; private ObjectType subclassOfUnresolvedNamedType; private FunctionType subclassCtor; private FunctionType interfaceType; private ObjectType interfaceInstType; private FunctionType subInterfaceType; private ObjectType subInterfaceInstType; private JSType recordType; private EnumType enumType; private EnumElementType elementsType; private NamedType forwardDeclaredNamedType; private static final StaticScope<JSType> EMPTY_SCOPE = MapBasedScope.emptyScope(); /** * A non exhaustive list of representative types used to test simple * properties that should hold for all types (such as the reflexivity * of subtyping). */ private List<JSType> types; @Override protected void setUp() throws Exception { super.setUp(); RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); recordType = builder.build(); enumType = new EnumType(registry, "Enum", null, NUMBER_TYPE); elementsType = enumType.getElementsType(); functionType = new FunctionBuilder(registry) .withReturnType(NUMBER_TYPE) .build(); dateMethod = new FunctionBuilder(registry) .withParamsNode(new Node(Token.PARAM_LIST)) .withReturnType(NUMBER_TYPE) .withTypeOfThis(DATE_TYPE) .build(); unresolvedNamedType = new NamedType(registry, "not.resolved.named.type", null, -1, -1); namedGoogBar = new NamedType(registry, "goog.Bar", null, -1, -1); subclassCtor = new FunctionType(registry, null, null, createArrowType(null), null, null, true, false); subclassCtor.setPrototypeBasedOn(unresolvedNamedType); subclassOfUnresolvedNamedType = subclassCtor.getInstanceType(); interfaceType = FunctionType.forInterface(registry, "Interface", null, registry.createTemplateTypeMap(null, null)); interfaceInstType = interfaceType.getInstanceType(); subInterfaceType = FunctionType.forInterface( registry, "SubInterface", null, registry.createTemplateTypeMap(null, null)); subInterfaceType.setExtendedInterfaces( Lists.<ObjectType>newArrayList(interfaceInstType)); subInterfaceInstType = subInterfaceType.getInstanceType(); googBar = registry.createConstructorType( "goog.Bar", null, null, null, null); googBar.getPrototype().defineDeclaredProperty("date", DATE_TYPE, null); googBar.setImplementedInterfaces( Lists.<ObjectType>newArrayList(interfaceInstType)); googBarInst = googBar.getInstanceType(); googSubBar = registry.createConstructorType( "googSubBar", null, null, null, null); googSubBar.setPrototypeBasedOn(googBar.getInstanceType()); googSubBarInst = googSubBar.getInstanceType(); googSubSubBar = registry.createConstructorType( "googSubSubBar", null, null, null, null); googSubSubBar.setPrototypeBasedOn(googSubBar.getInstanceType()); googSubSubBarInst = googSubSubBar.getInstanceType(); final ObjectType googObject = registry.createAnonymousObjectType(null); googObject.defineDeclaredProperty("Bar", googBar, null); namedGoogBar.resolve(null, new AbstractStaticScope<JSType>() { @Override public StaticSlot<JSType> getSlot(String name) { if ("goog".equals(name)) { return new SimpleSlot("goog", googObject, false); } else { return null; } } }); assertNotNull(namedGoogBar.getImplicitPrototype()); forwardDeclaredNamedType = new NamedType(registry, "forwardDeclared", "source", 1, 0); registry.forwardDeclareType("forwardDeclared"); forwardDeclaredNamedType.resolve( new SimpleErrorReporter(), EMPTY_SCOPE); types = ImmutableList.of( NO_OBJECT_TYPE, NO_RESOLVED_TYPE, NO_TYPE, BOOLEAN_OBJECT_TYPE, BOOLEAN_TYPE, STRING_OBJECT_TYPE, STRING_TYPE, VOID_TYPE, UNKNOWN_TYPE, NULL_TYPE, NUMBER_OBJECT_TYPE, NUMBER_TYPE, DATE_TYPE, ERROR_TYPE, SYNTAX_ERROR_TYPE, dateMethod, functionType, unresolvedNamedType, googBar, googSubBar, googSubSubBar, namedGoogBar, googBar.getInstanceType(), subclassOfUnresolvedNamedType, subclassCtor, recordType, enumType, elementsType, googBar, googSubBar, forwardDeclaredNamedType); } /** * Tests the behavior of the top constructor type. */ public void testUniversalConstructorType() throws Exception { // isXxx assertFalse(U2U_CONSTRUCTOR_TYPE.isNoObjectType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isNoType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isArrayType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isBooleanValueType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isDateType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isEnumElementType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isNullType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isNamedType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isNullType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isNumber()); assertFalse(U2U_CONSTRUCTOR_TYPE.isNumberObjectType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isNumberValueType()); assertTrue(U2U_CONSTRUCTOR_TYPE.isObject()); assertFalse(U2U_CONSTRUCTOR_TYPE.isFunctionPrototypeType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isRegexpType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isString()); assertFalse(U2U_CONSTRUCTOR_TYPE.isStringObjectType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isStringValueType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isEnumType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isUnionType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isStruct()); assertFalse(U2U_CONSTRUCTOR_TYPE.isDict()); assertFalse(U2U_CONSTRUCTOR_TYPE.isAllType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isVoidType()); assertTrue(U2U_CONSTRUCTOR_TYPE.isConstructor()); assertTrue(U2U_CONSTRUCTOR_TYPE.isInstanceType()); // isSubtype assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(NO_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(DATE_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(functionType)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(recordType)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(NULL_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(STRING_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(ALL_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(VOID_TYPE)); // canTestForEqualityWith assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(NO_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(NO_OBJECT_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(ALL_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(ARRAY_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(BOOLEAN_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(BOOLEAN_OBJECT_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(DATE_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(EVAL_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(functionType)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(recordType)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(NULL_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(NUMBER_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(OBJECT_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(URI_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(RANGE_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(REFERENCE_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(REGEXP_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(STRING_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(STRING_OBJECT_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(SYNTAX_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(TYPE_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(VOID_TYPE)); // canTestForShallowEqualityWith assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(NO_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(functionType)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(recordType)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(U2U_CONSTRUCTOR_TYPE.isNullable()); // isObject assertTrue(U2U_CONSTRUCTOR_TYPE.isObject()); // matchesXxx assertFalse(U2U_CONSTRUCTOR_TYPE.matchesInt32Context()); assertFalse(U2U_CONSTRUCTOR_TYPE.matchesNumberContext()); assertTrue(U2U_CONSTRUCTOR_TYPE.matchesObjectContext()); assertFalse(U2U_CONSTRUCTOR_TYPE.matchesStringContext()); assertFalse(U2U_CONSTRUCTOR_TYPE.matchesUint32Context()); // toString assertEquals("Function", U2U_CONSTRUCTOR_TYPE.toString()); assertTrue(U2U_CONSTRUCTOR_TYPE.hasDisplayName()); assertEquals("Function", U2U_CONSTRUCTOR_TYPE.getDisplayName()); // getPropertyType assertTypeEquals(UNKNOWN_TYPE, U2U_CONSTRUCTOR_TYPE.getPropertyType("anyProperty")); assertTrue(U2U_CONSTRUCTOR_TYPE.isNativeObjectType()); Asserts.assertResolvesToSame(U2U_CONSTRUCTOR_TYPE); assertTrue(U2U_CONSTRUCTOR_TYPE.isNominalConstructor()); } /** * Tests the behavior of the Bottom Object type. */ public void testNoObjectType() throws Exception { // isXxx assertTrue(NO_OBJECT_TYPE.isNoObjectType()); assertFalse(NO_OBJECT_TYPE.isNoType()); assertFalse(NO_OBJECT_TYPE.isArrayType()); assertFalse(NO_OBJECT_TYPE.isBooleanValueType()); assertFalse(NO_OBJECT_TYPE.isDateType()); assertFalse(NO_OBJECT_TYPE.isEnumElementType()); assertFalse(NO_OBJECT_TYPE.isNullType()); assertFalse(NO_OBJECT_TYPE.isNamedType()); assertFalse(NO_OBJECT_TYPE.isNullType()); assertTrue(NO_OBJECT_TYPE.isNumber()); assertFalse(NO_OBJECT_TYPE.isNumberObjectType()); assertFalse(NO_OBJECT_TYPE.isNumberValueType()); assertTrue(NO_OBJECT_TYPE.isObject()); assertFalse(NO_OBJECT_TYPE.isFunctionPrototypeType()); assertFalse(NO_OBJECT_TYPE.isRegexpType()); assertTrue(NO_OBJECT_TYPE.isString()); assertFalse(NO_OBJECT_TYPE.isStringObjectType()); assertFalse(NO_OBJECT_TYPE.isStringValueType()); assertFalse(NO_OBJECT_TYPE.isEnumType()); assertFalse(NO_OBJECT_TYPE.isUnionType()); assertFalse(NO_OBJECT_TYPE.isStruct()); assertFalse(NO_OBJECT_TYPE.isDict()); assertFalse(NO_OBJECT_TYPE.isAllType()); assertFalse(NO_OBJECT_TYPE.isVoidType()); assertTrue(NO_OBJECT_TYPE.isConstructor()); assertFalse(NO_OBJECT_TYPE.isInstanceType()); // isSubtype assertFalse(NO_OBJECT_TYPE.isSubtype(NO_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(BOOLEAN_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(DATE_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(functionType)); assertTrue(NO_OBJECT_TYPE.isSubtype(recordType)); assertFalse(NO_OBJECT_TYPE.isSubtype(NULL_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(NUMBER_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(URI_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(STRING_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(ALL_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(VOID_TYPE)); // canTestForEqualityWith assertCannotTestForEqualityWith(NO_OBJECT_TYPE, NO_TYPE); assertCannotTestForEqualityWith(NO_OBJECT_TYPE, NO_OBJECT_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, ALL_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, ARRAY_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, BOOLEAN_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, BOOLEAN_OBJECT_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, DATE_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, ERROR_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, EVAL_ERROR_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, functionType); assertCanTestForEqualityWith(NO_OBJECT_TYPE, recordType); assertCanTestForEqualityWith(NO_OBJECT_TYPE, NULL_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, NUMBER_OBJECT_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, URI_ERROR_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, RANGE_ERROR_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, REFERENCE_ERROR_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, STRING_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, SYNTAX_ERROR_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, TYPE_ERROR_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, VOID_TYPE); // canTestForShallowEqualityWith assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(NO_OBJECT_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue(NO_OBJECT_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(functionType)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(recordType)); assertFalse(NO_OBJECT_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(NO_OBJECT_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertTrue(NO_OBJECT_TYPE. canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(NO_OBJECT_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertTrue(NO_OBJECT_TYPE. canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE. canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(NO_OBJECT_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(NO_OBJECT_TYPE.isNullable()); // isObject assertTrue(NO_OBJECT_TYPE.isObject()); // matchesXxx assertTrue(NO_OBJECT_TYPE.matchesInt32Context()); assertTrue(NO_OBJECT_TYPE.matchesNumberContext()); assertTrue(NO_OBJECT_TYPE.matchesObjectContext()); assertTrue(NO_OBJECT_TYPE.matchesStringContext()); assertTrue(NO_OBJECT_TYPE.matchesUint32Context()); // toString assertEquals("NoObject", NO_OBJECT_TYPE.toString()); assertFalse(NO_OBJECT_TYPE.hasDisplayName()); assertEquals(null, NO_OBJECT_TYPE.getDisplayName()); // getPropertyType assertTypeEquals(NO_TYPE, NO_OBJECT_TYPE.getPropertyType("anyProperty")); Asserts.assertResolvesToSame(NO_OBJECT_TYPE); assertFalse(NO_OBJECT_TYPE.isNominalConstructor()); } /** * Tests the behavior of the Bottom type. */ public void testNoType() throws Exception { // isXxx assertFalse(NO_TYPE.isNoObjectType()); assertTrue(NO_TYPE.isNoType()); assertFalse(NO_TYPE.isArrayType()); assertFalse(NO_TYPE.isBooleanValueType()); assertFalse(NO_TYPE.isDateType()); assertFalse(NO_TYPE.isEnumElementType()); assertFalse(NO_TYPE.isNullType()); assertFalse(NO_TYPE.isNamedType()); assertFalse(NO_TYPE.isNullType()); assertTrue(NO_TYPE.isNumber()); assertFalse(NO_TYPE.isNumberObjectType()); assertFalse(NO_TYPE.isNumberValueType()); assertTrue(NO_TYPE.isObject()); assertFalse(NO_TYPE.isFunctionPrototypeType()); assertFalse(NO_TYPE.isRegexpType()); assertTrue(NO_TYPE.isString()); assertFalse(NO_TYPE.isStringObjectType()); assertFalse(NO_TYPE.isStringValueType()); assertFalse(NO_TYPE.isEnumType()); assertFalse(NO_TYPE.isUnionType()); assertFalse(NO_TYPE.isStruct()); assertFalse(NO_TYPE.isDict()); assertFalse(NO_TYPE.isAllType()); assertFalse(NO_TYPE.isVoidType()); assertTrue(NO_TYPE.isConstructor()); assertFalse(NO_TYPE.isInstanceType()); // isSubtype assertTrue(NO_TYPE.isSubtype(NO_TYPE)); assertTrue(NO_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(ARRAY_TYPE)); assertTrue(NO_TYPE.isSubtype(BOOLEAN_TYPE)); assertTrue(NO_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(DATE_TYPE)); assertTrue(NO_TYPE.isSubtype(ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(functionType)); assertTrue(NO_TYPE.isSubtype(NULL_TYPE)); assertTrue(NO_TYPE.isSubtype(NUMBER_TYPE)); assertTrue(NO_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(URI_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(REGEXP_TYPE)); assertTrue(NO_TYPE.isSubtype(STRING_TYPE)); assertTrue(NO_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(ALL_TYPE)); assertTrue(NO_TYPE.isSubtype(VOID_TYPE)); // canTestForEqualityWith assertCannotTestForEqualityWith(NO_TYPE, NO_TYPE); assertCannotTestForEqualityWith(NO_TYPE, NO_OBJECT_TYPE); assertCanTestForEqualityWith(NO_TYPE, ARRAY_TYPE); assertCanTestForEqualityWith(NO_TYPE, BOOLEAN_TYPE); assertCanTestForEqualityWith(NO_TYPE, BOOLEAN_OBJECT_TYPE); assertCanTestForEqualityWith(NO_TYPE, DATE_TYPE); assertCanTestForEqualityWith(NO_TYPE, ERROR_TYPE); assertCanTestForEqualityWith(NO_TYPE, EVAL_ERROR_TYPE); assertCanTestForEqualityWith(NO_TYPE, functionType); assertCanTestForEqualityWith(NO_TYPE, NULL_TYPE); assertCanTestForEqualityWith(NO_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(NO_TYPE, NUMBER_OBJECT_TYPE); assertCanTestForEqualityWith(NO_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(NO_TYPE, URI_ERROR_TYPE); assertCanTestForEqualityWith(NO_TYPE, RANGE_ERROR_TYPE); assertCanTestForEqualityWith(NO_TYPE, REFERENCE_ERROR_TYPE); assertCanTestForEqualityWith(NO_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(NO_TYPE, STRING_TYPE); assertCanTestForEqualityWith(NO_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(NO_TYPE, SYNTAX_ERROR_TYPE); assertCanTestForEqualityWith(NO_TYPE, TYPE_ERROR_TYPE); assertCanTestForEqualityWith(NO_TYPE, ALL_TYPE); assertCanTestForEqualityWith(NO_TYPE, VOID_TYPE); // canTestForShallowEqualityWith assertTrue(NO_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(functionType)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertTrue(NO_TYPE.isNullable()); // isObject assertTrue(NO_TYPE.isObject()); // matchesXxx assertTrue(NO_TYPE.matchesInt32Context()); assertTrue(NO_TYPE.matchesNumberContext()); assertTrue(NO_TYPE.matchesObjectContext()); assertTrue(NO_TYPE.matchesStringContext()); assertTrue(NO_TYPE.matchesUint32Context()); // toString assertEquals("None", NO_TYPE.toString()); assertEquals(null, NO_TYPE.getDisplayName()); assertFalse(NO_TYPE.hasDisplayName()); // getPropertyType assertTypeEquals(NO_TYPE, NO_TYPE.getPropertyType("anyProperty")); Asserts.assertResolvesToSame(NO_TYPE); assertFalse(NO_TYPE.isNominalConstructor()); } /** * Tests the behavior of the unresolved Bottom type. */ public void testNoResolvedType() throws Exception { // isXxx assertFalse(NO_RESOLVED_TYPE.isNoObjectType()); assertFalse(NO_RESOLVED_TYPE.isNoType()); assertTrue(NO_RESOLVED_TYPE.isNoResolvedType()); assertFalse(NO_RESOLVED_TYPE.isArrayType()); assertFalse(NO_RESOLVED_TYPE.isBooleanValueType()); assertFalse(NO_RESOLVED_TYPE.isDateType()); assertFalse(NO_RESOLVED_TYPE.isEnumElementType()); assertFalse(NO_RESOLVED_TYPE.isNullType()); assertFalse(NO_RESOLVED_TYPE.isNamedType()); assertTrue(NO_RESOLVED_TYPE.isNumber()); assertFalse(NO_RESOLVED_TYPE.isNumberObjectType()); assertFalse(NO_RESOLVED_TYPE.isNumberValueType()); assertTrue(NO_RESOLVED_TYPE.isObject()); assertFalse(NO_RESOLVED_TYPE.isFunctionPrototypeType()); assertFalse(NO_RESOLVED_TYPE.isRegexpType()); assertTrue(NO_RESOLVED_TYPE.isString()); assertFalse(NO_RESOLVED_TYPE.isStringObjectType()); assertFalse(NO_RESOLVED_TYPE.isStringValueType()); assertFalse(NO_RESOLVED_TYPE.isEnumType()); assertFalse(NO_RESOLVED_TYPE.isUnionType()); assertFalse(NO_RESOLVED_TYPE.isStruct()); assertFalse(NO_RESOLVED_TYPE.isDict()); assertFalse(NO_RESOLVED_TYPE.isAllType()); assertFalse(NO_RESOLVED_TYPE.isVoidType()); assertFalse(NO_RESOLVED_TYPE.isConstructor()); assertFalse(NO_RESOLVED_TYPE.isInstanceType()); // isSubtype assertTrue(NO_RESOLVED_TYPE.isSubtype(NO_RESOLVED_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(ARRAY_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(BOOLEAN_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(DATE_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(functionType)); assertTrue(NO_RESOLVED_TYPE.isSubtype(NULL_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(NUMBER_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(URI_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(REGEXP_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(STRING_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(ALL_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(VOID_TYPE)); // canTestForEqualityWith assertCanTestForEqualityWith(NO_RESOLVED_TYPE, NO_RESOLVED_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, NO_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, NO_OBJECT_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, ARRAY_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, BOOLEAN_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, BOOLEAN_OBJECT_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, DATE_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, ERROR_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, EVAL_ERROR_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, functionType); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, NULL_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, NUMBER_OBJECT_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, URI_ERROR_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, RANGE_ERROR_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, REFERENCE_ERROR_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, STRING_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, SYNTAX_ERROR_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, TYPE_ERROR_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, ALL_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, VOID_TYPE); // canTestForShallowEqualityWith assertTrue( NO_RESOLVED_TYPE.canTestForShallowEqualityWith(NO_RESOLVED_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue( NO_RESOLVED_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(functionType)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertTrue( NO_RESOLVED_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertTrue( NO_RESOLVED_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertTrue( NO_RESOLVED_TYPE.canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertTrue( NO_RESOLVED_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertTrue( NO_RESOLVED_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertTrue(NO_RESOLVED_TYPE.isNullable()); // isObject assertTrue(NO_RESOLVED_TYPE.isObject()); // matchesXxx assertTrue(NO_RESOLVED_TYPE.matchesInt32Context()); assertTrue(NO_RESOLVED_TYPE.matchesNumberContext()); assertTrue(NO_RESOLVED_TYPE.matchesObjectContext()); assertTrue(NO_RESOLVED_TYPE.matchesStringContext()); assertTrue(NO_RESOLVED_TYPE.matchesUint32Context()); // toString assertEquals("NoResolvedType", NO_RESOLVED_TYPE.toString()); assertEquals(null, NO_RESOLVED_TYPE.getDisplayName()); assertFalse(NO_RESOLVED_TYPE.hasDisplayName()); // getPropertyType assertTypeEquals(CHECKED_UNKNOWN_TYPE, NO_RESOLVED_TYPE.getPropertyType("anyProperty")); Asserts.assertResolvesToSame(NO_RESOLVED_TYPE); assertTrue(forwardDeclaredNamedType.isEmptyType()); assertTrue(forwardDeclaredNamedType.isNoResolvedType()); UnionType nullable = (UnionType) registry.createNullableType(NO_RESOLVED_TYPE); assertTypeEquals( nullable, nullable.getGreatestSubtype(NULL_TYPE)); assertTypeEquals(NO_RESOLVED_TYPE, nullable.getRestrictedUnion(NULL_TYPE)); } /** * Tests the behavior of the Array type. */ public void testArrayType() throws Exception { // isXxx assertTrue(ARRAY_TYPE.isArrayType()); assertFalse(ARRAY_TYPE.isBooleanValueType()); assertFalse(ARRAY_TYPE.isDateType()); assertFalse(ARRAY_TYPE.isEnumElementType()); assertFalse(ARRAY_TYPE.isNamedType()); assertFalse(ARRAY_TYPE.isNullType()); assertFalse(ARRAY_TYPE.isNumber()); assertFalse(ARRAY_TYPE.isNumberObjectType()); assertFalse(ARRAY_TYPE.isNumberValueType()); assertTrue(ARRAY_TYPE.isObject()); assertFalse(ARRAY_TYPE.isFunctionPrototypeType()); assertTrue(ARRAY_TYPE.getImplicitPrototype().isFunctionPrototypeType()); assertFalse(ARRAY_TYPE.isRegexpType()); assertFalse(ARRAY_TYPE.isString()); assertFalse(ARRAY_TYPE.isStringObjectType()); assertFalse(ARRAY_TYPE.isStringValueType()); assertFalse(ARRAY_TYPE.isEnumType()); assertFalse(ARRAY_TYPE.isUnionType()); assertFalse(ARRAY_TYPE.isStruct()); assertFalse(ARRAY_TYPE.isDict()); assertFalse(ARRAY_TYPE.isAllType()); assertFalse(ARRAY_TYPE.isVoidType()); assertFalse(ARRAY_TYPE.isConstructor()); assertTrue(ARRAY_TYPE.isInstanceType()); // isSubtype assertFalse(ARRAY_TYPE.isSubtype(NO_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(ARRAY_TYPE.isSubtype(ALL_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(functionType)); assertFalse(ARRAY_TYPE.isSubtype(recordType)); assertFalse(ARRAY_TYPE.isSubtype(NULL_TYPE)); assertTrue(ARRAY_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(DATE_TYPE)); assertTrue(ARRAY_TYPE.isSubtype(unresolvedNamedType)); assertFalse(ARRAY_TYPE.isSubtype(namedGoogBar)); assertFalse(ARRAY_TYPE.isSubtype(REGEXP_TYPE)); // canBeCalled assertFalse(ARRAY_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(ARRAY_TYPE, NO_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, NO_OBJECT_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, ALL_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, functionType); assertCanTestForEqualityWith(ARRAY_TYPE, recordType); assertCannotTestForEqualityWith(ARRAY_TYPE, VOID_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, DATE_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(ARRAY_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(ARRAY_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertTrue(ARRAY_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(recordType)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(ARRAY_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(ARRAY_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(ARRAY_TYPE.isNullable()); assertTrue(createUnionType(ARRAY_TYPE, NULL_TYPE).isNullable()); // isObject assertTrue(ARRAY_TYPE.isObject()); // getLeastSupertype assertTypeEquals(ALL_TYPE, ARRAY_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(createUnionType(STRING_OBJECT_TYPE, ARRAY_TYPE), ARRAY_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(createUnionType(NUMBER_TYPE, ARRAY_TYPE), ARRAY_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(createUnionType(ARRAY_TYPE, functionType), ARRAY_TYPE.getLeastSupertype(functionType)); assertTypeEquals(OBJECT_TYPE, ARRAY_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(createUnionType(DATE_TYPE, ARRAY_TYPE), ARRAY_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(createUnionType(REGEXP_TYPE, ARRAY_TYPE), ARRAY_TYPE.getLeastSupertype(REGEXP_TYPE)); // getPropertyType assertEquals(17, ARRAY_TYPE.getImplicitPrototype().getPropertiesCount()); assertEquals(18, ARRAY_TYPE.getPropertiesCount()); assertReturnTypeEquals(ARRAY_TYPE, ARRAY_TYPE.getPropertyType("constructor")); assertReturnTypeEquals(STRING_TYPE, ARRAY_TYPE.getPropertyType("toString")); assertReturnTypeEquals(STRING_TYPE, ARRAY_TYPE.getPropertyType("toLocaleString")); assertReturnTypeEquals(ARRAY_TYPE, ARRAY_TYPE.getPropertyType("concat")); assertReturnTypeEquals(STRING_TYPE, ARRAY_TYPE.getPropertyType("join")); assertReturnTypeEquals(UNKNOWN_TYPE, ARRAY_TYPE.getPropertyType("pop")); assertReturnTypeEquals(NUMBER_TYPE, ARRAY_TYPE.getPropertyType("push")); assertReturnTypeEquals(ARRAY_TYPE, ARRAY_TYPE.getPropertyType("reverse")); assertReturnTypeEquals(UNKNOWN_TYPE, ARRAY_TYPE.getPropertyType("shift")); assertReturnTypeEquals(ARRAY_TYPE, ARRAY_TYPE.getPropertyType("slice")); assertReturnTypeEquals(ARRAY_TYPE, ARRAY_TYPE.getPropertyType("sort")); assertReturnTypeEquals(ARRAY_TYPE, ARRAY_TYPE.getPropertyType("splice")); assertReturnTypeEquals(NUMBER_TYPE, ARRAY_TYPE.getPropertyType("unshift")); assertTypeEquals(NUMBER_TYPE, ARRAY_TYPE.getPropertyType("length")); // isPropertyType* assertPropertyTypeDeclared(ARRAY_TYPE, "pop"); // matchesXxx assertFalse(ARRAY_TYPE.matchesInt32Context()); assertFalse(ARRAY_TYPE.matchesNumberContext()); assertTrue(ARRAY_TYPE.matchesObjectContext()); assertTrue(ARRAY_TYPE.matchesStringContext()); assertFalse(ARRAY_TYPE.matchesUint32Context()); // toString assertEquals("Array", ARRAY_TYPE.toString()); assertTrue(ARRAY_TYPE.hasDisplayName()); assertEquals("Array", ARRAY_TYPE.getDisplayName()); assertTrue(ARRAY_TYPE.isNativeObjectType()); Asserts.assertResolvesToSame(ARRAY_TYPE); assertFalse(ARRAY_TYPE.isNominalConstructor()); assertTrue(ARRAY_TYPE.getConstructor().isNominalConstructor()); } /** * Tests the behavior of the unknown type. */ public void testUnknownType() throws Exception { // isXxx assertFalse(UNKNOWN_TYPE.isArrayType()); assertFalse(UNKNOWN_TYPE.isBooleanObjectType()); assertFalse(UNKNOWN_TYPE.isBooleanValueType()); assertFalse(UNKNOWN_TYPE.isDateType()); assertFalse(UNKNOWN_TYPE.isEnumElementType()); assertFalse(UNKNOWN_TYPE.isNamedType()); assertFalse(UNKNOWN_TYPE.isNullType()); assertFalse(UNKNOWN_TYPE.isNumberObjectType()); assertFalse(UNKNOWN_TYPE.isNumberValueType()); assertTrue(UNKNOWN_TYPE.isObject()); assertFalse(UNKNOWN_TYPE.isFunctionPrototypeType()); assertFalse(UNKNOWN_TYPE.isRegexpType()); assertFalse(UNKNOWN_TYPE.isStringObjectType()); assertFalse(UNKNOWN_TYPE.isStringValueType()); assertFalse(UNKNOWN_TYPE.isEnumType()); assertFalse(UNKNOWN_TYPE.isUnionType()); assertFalse(UNKNOWN_TYPE.isStruct()); assertFalse(UNKNOWN_TYPE.isDict()); assertTrue(UNKNOWN_TYPE.isUnknownType()); assertFalse(UNKNOWN_TYPE.isVoidType()); assertFalse(UNKNOWN_TYPE.isConstructor()); assertFalse(UNKNOWN_TYPE.isInstanceType()); // autoboxesTo assertNull(UNKNOWN_TYPE.autoboxesTo()); // isSubtype assertTrue(UNKNOWN_TYPE.isSubtype(UNKNOWN_TYPE)); assertTrue(UNKNOWN_TYPE.isSubtype(STRING_TYPE)); assertTrue(UNKNOWN_TYPE.isSubtype(NUMBER_TYPE)); assertTrue(UNKNOWN_TYPE.isSubtype(functionType)); assertTrue(UNKNOWN_TYPE.isSubtype(recordType)); assertTrue(UNKNOWN_TYPE.isSubtype(NULL_TYPE)); assertTrue(UNKNOWN_TYPE.isSubtype(OBJECT_TYPE)); assertTrue(UNKNOWN_TYPE.isSubtype(DATE_TYPE)); assertTrue(UNKNOWN_TYPE.isSubtype(namedGoogBar)); assertTrue(UNKNOWN_TYPE.isSubtype(unresolvedNamedType)); assertTrue(UNKNOWN_TYPE.isSubtype(REGEXP_TYPE)); assertTrue(UNKNOWN_TYPE.isSubtype(VOID_TYPE)); // canBeCalled assertTrue(UNKNOWN_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(UNKNOWN_TYPE, UNKNOWN_TYPE); assertCanTestForEqualityWith(UNKNOWN_TYPE, STRING_TYPE); assertCanTestForEqualityWith(UNKNOWN_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(UNKNOWN_TYPE, functionType); assertCanTestForEqualityWith(UNKNOWN_TYPE, recordType); assertCanTestForEqualityWith(UNKNOWN_TYPE, VOID_TYPE); assertCanTestForEqualityWith(UNKNOWN_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(UNKNOWN_TYPE, DATE_TYPE); assertCanTestForEqualityWith(UNKNOWN_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(UNKNOWN_TYPE, BOOLEAN_TYPE); // canTestForShallowEqualityWith assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(UNKNOWN_TYPE)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(functionType)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(recordType)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); // canHaveNullValue assertTrue(UNKNOWN_TYPE.isNullable()); // getGreatestCommonType assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(UNKNOWN_TYPE)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(STRING_TYPE)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(functionType)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(REGEXP_TYPE)); // matchesXxx assertTrue(UNKNOWN_TYPE.matchesInt32Context()); assertTrue(UNKNOWN_TYPE.matchesNumberContext()); assertTrue(UNKNOWN_TYPE.matchesObjectContext()); assertTrue(UNKNOWN_TYPE.matchesStringContext()); assertTrue(UNKNOWN_TYPE.matchesUint32Context()); // isPropertyType* assertPropertyTypeUnknown(UNKNOWN_TYPE, "XXX"); // toString assertEquals("?", UNKNOWN_TYPE.toString()); assertTrue(UNKNOWN_TYPE.hasDisplayName()); assertEquals("Unknown", UNKNOWN_TYPE.getDisplayName()); Asserts.assertResolvesToSame(UNKNOWN_TYPE); assertFalse(UNKNOWN_TYPE.isNominalConstructor()); assertEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getPropertyType("abc")); } /** * Tests the behavior of the checked unknown type. */ public void testCheckedUnknownType() throws Exception { // isPropertyType* assertPropertyTypeUnknown(CHECKED_UNKNOWN_TYPE, "XXX"); // toString assertEquals("??", CHECKED_UNKNOWN_TYPE.toString()); assertTrue(CHECKED_UNKNOWN_TYPE.hasDisplayName()); assertEquals("Unknown", CHECKED_UNKNOWN_TYPE.getDisplayName()); Asserts.assertResolvesToSame(CHECKED_UNKNOWN_TYPE); assertFalse(CHECKED_UNKNOWN_TYPE.isNominalConstructor()); assertEquals(CHECKED_UNKNOWN_TYPE, CHECKED_UNKNOWN_TYPE.getPropertyType("abc")); } /** * Tests the behavior of the unknown type. */ public void testAllType() throws Exception { // isXxx assertFalse(ALL_TYPE.isArrayType()); assertFalse(ALL_TYPE.isBooleanValueType()); assertFalse(ALL_TYPE.isDateType()); assertFalse(ALL_TYPE.isEnumElementType()); assertFalse(ALL_TYPE.isNamedType()); assertFalse(ALL_TYPE.isNullType()); assertFalse(ALL_TYPE.isNumber()); assertFalse(ALL_TYPE.isNumberObjectType()); assertFalse(ALL_TYPE.isNumberValueType()); assertFalse(ALL_TYPE.isObject()); assertFalse(ALL_TYPE.isFunctionPrototypeType()); assertFalse(ALL_TYPE.isRegexpType()); assertFalse(ALL_TYPE.isString()); assertFalse(ALL_TYPE.isStringObjectType()); assertFalse(ALL_TYPE.isStringValueType()); assertFalse(ALL_TYPE.isEnumType()); assertFalse(ALL_TYPE.isUnionType()); assertFalse(ALL_TYPE.isStruct()); assertFalse(ALL_TYPE.isDict()); assertTrue(ALL_TYPE.isAllType()); assertFalse(ALL_TYPE.isVoidType()); assertFalse(ALL_TYPE.isConstructor()); assertFalse(ALL_TYPE.isInstanceType()); // isSubtype assertFalse(ALL_TYPE.isSubtype(NO_TYPE)); assertFalse(ALL_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(ALL_TYPE.isSubtype(ALL_TYPE)); assertFalse(ALL_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(ALL_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(ALL_TYPE.isSubtype(functionType)); assertFalse(ALL_TYPE.isSubtype(recordType)); assertFalse(ALL_TYPE.isSubtype(NULL_TYPE)); assertFalse(ALL_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(ALL_TYPE.isSubtype(DATE_TYPE)); assertTrue(ALL_TYPE.isSubtype(unresolvedNamedType)); assertFalse(ALL_TYPE.isSubtype(namedGoogBar)); assertFalse(ALL_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(ALL_TYPE.isSubtype(VOID_TYPE)); assertTrue(ALL_TYPE.isSubtype(UNKNOWN_TYPE)); // canBeCalled assertFalse(ALL_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(ALL_TYPE, ALL_TYPE); assertCanTestForEqualityWith(ALL_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(ALL_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(ALL_TYPE, functionType); assertCanTestForEqualityWith(ALL_TYPE, recordType); assertCanTestForEqualityWith(ALL_TYPE, VOID_TYPE); assertCanTestForEqualityWith(ALL_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(ALL_TYPE, DATE_TYPE); assertCanTestForEqualityWith(ALL_TYPE, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(ALL_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(functionType)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(recordType)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(ALL_TYPE.isNullable()); // getLeastSupertype assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(UNKNOWN_TYPE)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(functionType)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(REGEXP_TYPE)); // matchesXxx assertFalse(ALL_TYPE.matchesInt32Context()); assertFalse(ALL_TYPE.matchesNumberContext()); assertTrue(ALL_TYPE.matchesObjectContext()); assertTrue(ALL_TYPE.matchesStringContext()); assertFalse(ALL_TYPE.matchesUint32Context()); // toString assertEquals("*", ALL_TYPE.toString()); assertTrue(ALL_TYPE.hasDisplayName()); assertEquals("<Any Type>", ALL_TYPE.getDisplayName()); Asserts.assertResolvesToSame(ALL_TYPE); assertFalse(ALL_TYPE.isNominalConstructor()); } /** * Tests the behavior of the Object type (the object * at the top of the JavaScript hierarchy). */ public void testTheObjectType() throws Exception { // implicit prototype assertTypeEquals(OBJECT_PROTOTYPE, OBJECT_TYPE.getImplicitPrototype()); // isXxx assertFalse(OBJECT_TYPE.isNoObjectType()); assertFalse(OBJECT_TYPE.isNoType()); assertFalse(OBJECT_TYPE.isArrayType()); assertFalse(OBJECT_TYPE.isBooleanValueType()); assertFalse(OBJECT_TYPE.isDateType()); assertFalse(OBJECT_TYPE.isEnumElementType()); assertFalse(OBJECT_TYPE.isNullType()); assertFalse(OBJECT_TYPE.isNamedType()); assertFalse(OBJECT_TYPE.isNullType()); assertFalse(OBJECT_TYPE.isNumber()); assertFalse(OBJECT_TYPE.isNumberObjectType()); assertFalse(OBJECT_TYPE.isNumberValueType()); assertTrue(OBJECT_TYPE.isObject()); assertFalse(OBJECT_TYPE.isFunctionPrototypeType()); assertTrue(OBJECT_TYPE.getImplicitPrototype().isFunctionPrototypeType()); assertFalse(OBJECT_TYPE.isRegexpType()); assertFalse(OBJECT_TYPE.isString()); assertFalse(OBJECT_TYPE.isStringObjectType()); assertFalse(OBJECT_TYPE.isStringValueType()); assertFalse(OBJECT_TYPE.isEnumType()); assertFalse(OBJECT_TYPE.isUnionType()); assertFalse(OBJECT_TYPE.isStruct()); assertFalse(OBJECT_TYPE.isDict()); assertFalse(OBJECT_TYPE.isAllType()); assertFalse(OBJECT_TYPE.isVoidType()); assertFalse(OBJECT_TYPE.isConstructor()); assertTrue(OBJECT_TYPE.isInstanceType()); // isSubtype assertFalse(OBJECT_TYPE.isSubtype(NO_TYPE)); assertTrue(OBJECT_TYPE.isSubtype(ALL_TYPE)); assertFalse(OBJECT_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(OBJECT_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(OBJECT_TYPE.isSubtype(functionType)); assertFalse(OBJECT_TYPE.isSubtype(recordType)); assertFalse(OBJECT_TYPE.isSubtype(NULL_TYPE)); assertTrue(OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(OBJECT_TYPE.isSubtype(DATE_TYPE)); assertFalse(OBJECT_TYPE.isSubtype(namedGoogBar)); assertTrue(OBJECT_TYPE.isSubtype(unresolvedNamedType)); assertFalse(OBJECT_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(OBJECT_TYPE.isSubtype(ARRAY_TYPE)); assertTrue(OBJECT_TYPE.isSubtype(UNKNOWN_TYPE)); // canBeCalled assertFalse(OBJECT_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(OBJECT_TYPE, ALL_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, STRING_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, BOOLEAN_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, functionType); assertCanTestForEqualityWith(OBJECT_TYPE, recordType); assertCannotTestForEqualityWith(OBJECT_TYPE, VOID_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, DATE_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, ARRAY_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, UNKNOWN_TYPE); // canTestForShallowEqualityWith assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(OBJECT_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(functionType)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(recordType)); assertFalse(OBJECT_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(OBJECT_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertTrue(OBJECT_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(OBJECT_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(OBJECT_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // isNullable assertFalse(OBJECT_TYPE.isNullable()); // getLeastSupertype assertTypeEquals(ALL_TYPE, OBJECT_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(OBJECT_TYPE, OBJECT_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(createUnionType(OBJECT_TYPE, NUMBER_TYPE), OBJECT_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(OBJECT_TYPE, OBJECT_TYPE.getLeastSupertype(functionType)); assertTypeEquals(OBJECT_TYPE, OBJECT_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(OBJECT_TYPE, OBJECT_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(OBJECT_TYPE, OBJECT_TYPE.getLeastSupertype(REGEXP_TYPE)); // getPropertyType assertEquals(7, OBJECT_TYPE.getPropertiesCount()); assertReturnTypeEquals(OBJECT_TYPE, OBJECT_TYPE.getPropertyType("constructor")); assertReturnTypeEquals(STRING_TYPE, OBJECT_TYPE.getPropertyType("toString")); assertReturnTypeEquals(STRING_TYPE, OBJECT_TYPE.getPropertyType("toLocaleString")); assertReturnTypeEquals(UNKNOWN_TYPE, OBJECT_TYPE.getPropertyType("valueOf")); assertReturnTypeEquals(BOOLEAN_TYPE, OBJECT_TYPE.getPropertyType("hasOwnProperty")); assertReturnTypeEquals(BOOLEAN_TYPE, OBJECT_TYPE.getPropertyType("isPrototypeOf")); assertReturnTypeEquals(BOOLEAN_TYPE, OBJECT_TYPE.getPropertyType("propertyIsEnumerable")); // matchesXxx assertFalse(OBJECT_TYPE.matchesInt32Context()); assertFalse(OBJECT_TYPE.matchesNumberContext()); assertTrue(OBJECT_TYPE.matchesObjectContext()); assertTrue(OBJECT_TYPE.matchesStringContext()); assertFalse(OBJECT_TYPE.matchesUint32Context()); // implicit prototype assertTypeEquals(OBJECT_PROTOTYPE, OBJECT_TYPE.getImplicitPrototype()); // toString assertEquals("Object", OBJECT_TYPE.toString()); assertTrue(OBJECT_TYPE.isNativeObjectType()); assertTrue(OBJECT_TYPE.getImplicitPrototype().isNativeObjectType()); Asserts.assertResolvesToSame(OBJECT_TYPE); assertFalse(OBJECT_TYPE.isNominalConstructor()); assertTrue(OBJECT_TYPE.getConstructor().isNominalConstructor()); } /** * Tests the behavior of the number value type. */ public void testNumberObjectType() throws Exception { // isXxx assertFalse(NUMBER_OBJECT_TYPE.isArrayType()); assertFalse(NUMBER_OBJECT_TYPE.isBooleanObjectType()); assertFalse(NUMBER_OBJECT_TYPE.isBooleanValueType()); assertFalse(NUMBER_OBJECT_TYPE.isDateType()); assertFalse(NUMBER_OBJECT_TYPE.isEnumElementType()); assertFalse(NUMBER_OBJECT_TYPE.isNamedType()); assertFalse(NUMBER_OBJECT_TYPE.isNullType()); assertTrue(NUMBER_OBJECT_TYPE.isNumber()); assertTrue(NUMBER_OBJECT_TYPE.isNumberObjectType()); assertFalse(NUMBER_OBJECT_TYPE.isNumberValueType()); assertTrue(NUMBER_OBJECT_TYPE.isObject()); assertFalse(NUMBER_OBJECT_TYPE.isFunctionPrototypeType()); assertTrue( NUMBER_OBJECT_TYPE.getImplicitPrototype().isFunctionPrototypeType()); assertFalse(NUMBER_OBJECT_TYPE.isRegexpType()); assertFalse(NUMBER_OBJECT_TYPE.isString()); assertFalse(NUMBER_OBJECT_TYPE.isStringObjectType()); assertFalse(NUMBER_OBJECT_TYPE.isStringValueType()); assertFalse(NUMBER_OBJECT_TYPE.isEnumType()); assertFalse(NUMBER_OBJECT_TYPE.isUnionType()); assertFalse(NUMBER_OBJECT_TYPE.isStruct()); assertFalse(NUMBER_OBJECT_TYPE.isDict()); assertFalse(NUMBER_OBJECT_TYPE.isAllType()); assertFalse(NUMBER_OBJECT_TYPE.isVoidType()); assertFalse(NUMBER_OBJECT_TYPE.isConstructor()); assertTrue(NUMBER_OBJECT_TYPE.isInstanceType()); // autoboxesTo assertTypeEquals(NUMBER_OBJECT_TYPE, NUMBER_TYPE.autoboxesTo()); // unboxesTo assertTypeEquals(NUMBER_TYPE, NUMBER_OBJECT_TYPE.unboxesTo()); // isSubtype assertTrue(NUMBER_OBJECT_TYPE.isSubtype(ALL_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.isSubtype(functionType)); assertFalse(NUMBER_OBJECT_TYPE.isSubtype(NULL_TYPE)); assertTrue(NUMBER_OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.isSubtype(DATE_TYPE)); assertTrue(NUMBER_OBJECT_TYPE.isSubtype(unresolvedNamedType)); assertFalse(NUMBER_OBJECT_TYPE.isSubtype(namedGoogBar)); assertTrue(NUMBER_OBJECT_TYPE.isSubtype( createUnionType(NUMBER_OBJECT_TYPE, NULL_TYPE))); assertFalse(NUMBER_OBJECT_TYPE.isSubtype( createUnionType(NUMBER_TYPE, NULL_TYPE))); assertTrue(NUMBER_OBJECT_TYPE.isSubtype(UNKNOWN_TYPE)); // canBeCalled assertFalse(NUMBER_OBJECT_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, NO_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, NO_OBJECT_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, ALL_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, functionType); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, elementsType); assertCannotTestForEqualityWith(NUMBER_OBJECT_TYPE, VOID_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, DATE_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, ARRAY_TYPE); // canTestForShallowEqualityWith assertTrue(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertTrue(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(NUMBER_OBJECT_TYPE.isNullable()); // getLeastSupertype assertTypeEquals(ALL_TYPE, NUMBER_OBJECT_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(createUnionType(NUMBER_OBJECT_TYPE, STRING_OBJECT_TYPE), NUMBER_OBJECT_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(createUnionType(NUMBER_OBJECT_TYPE, NUMBER_TYPE), NUMBER_OBJECT_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(createUnionType(NUMBER_OBJECT_TYPE, functionType), NUMBER_OBJECT_TYPE.getLeastSupertype(functionType)); assertTypeEquals(OBJECT_TYPE, NUMBER_OBJECT_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(createUnionType(NUMBER_OBJECT_TYPE, DATE_TYPE), NUMBER_OBJECT_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(createUnionType(NUMBER_OBJECT_TYPE, REGEXP_TYPE), NUMBER_OBJECT_TYPE.getLeastSupertype(REGEXP_TYPE)); // matchesXxx assertTrue(NUMBER_OBJECT_TYPE.matchesInt32Context()); assertTrue(NUMBER_OBJECT_TYPE.matchesNumberContext()); assertTrue(NUMBER_OBJECT_TYPE.matchesObjectContext()); assertTrue(NUMBER_OBJECT_TYPE.matchesStringContext()); assertTrue(NUMBER_OBJECT_TYPE.matchesUint32Context()); // toString assertEquals("Number", NUMBER_OBJECT_TYPE.toString()); assertTrue(NUMBER_OBJECT_TYPE.hasDisplayName()); assertEquals("Number", NUMBER_OBJECT_TYPE.getDisplayName()); assertTrue(NUMBER_OBJECT_TYPE.isNativeObjectType()); Asserts.assertResolvesToSame(NUMBER_OBJECT_TYPE); } /** * Tests the behavior of the number value type. */ public void testNumberValueType() throws Exception { // isXxx assertFalse(NUMBER_TYPE.isArrayType()); assertFalse(NUMBER_TYPE.isBooleanObjectType()); assertFalse(NUMBER_TYPE.isBooleanValueType()); assertFalse(NUMBER_TYPE.isDateType()); assertFalse(NUMBER_TYPE.isEnumElementType()); assertFalse(NUMBER_TYPE.isNamedType()); assertFalse(NUMBER_TYPE.isNullType()); assertTrue(NUMBER_TYPE.isNumber()); assertFalse(NUMBER_TYPE.isNumberObjectType()); assertTrue(NUMBER_TYPE.isNumberValueType()); assertFalse(NUMBER_TYPE.isFunctionPrototypeType()); assertFalse(NUMBER_TYPE.isRegexpType()); assertFalse(NUMBER_TYPE.isString()); assertFalse(NUMBER_TYPE.isStringObjectType()); assertFalse(NUMBER_TYPE.isStringValueType()); assertFalse(NUMBER_TYPE.isEnumType()); assertFalse(NUMBER_TYPE.isUnionType()); assertFalse(NUMBER_TYPE.isStruct()); assertFalse(NUMBER_TYPE.isDict()); assertFalse(NUMBER_TYPE.isAllType()); assertFalse(NUMBER_TYPE.isVoidType()); assertFalse(NUMBER_TYPE.isConstructor()); assertFalse(NUMBER_TYPE.isInstanceType()); // autoboxesTo assertTypeEquals(NUMBER_OBJECT_TYPE, NUMBER_TYPE.autoboxesTo()); // isSubtype assertTrue(NUMBER_TYPE.isSubtype(ALL_TYPE)); assertFalse(NUMBER_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertTrue(NUMBER_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(NUMBER_TYPE.isSubtype(functionType)); assertFalse(NUMBER_TYPE.isSubtype(NULL_TYPE)); assertFalse(NUMBER_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(NUMBER_TYPE.isSubtype(DATE_TYPE)); assertTrue(NUMBER_TYPE.isSubtype(unresolvedNamedType)); assertFalse(NUMBER_TYPE.isSubtype(namedGoogBar)); assertTrue(NUMBER_TYPE.isSubtype( createUnionType(NUMBER_TYPE, NULL_TYPE))); assertTrue(NUMBER_TYPE.isSubtype(UNKNOWN_TYPE)); // canBeCalled assertFalse(NUMBER_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(NUMBER_TYPE, NO_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, NO_OBJECT_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, ALL_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, STRING_OBJECT_TYPE); assertCannotTestForEqualityWith(NUMBER_TYPE, functionType); assertCannotTestForEqualityWith(NUMBER_TYPE, VOID_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, DATE_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, ARRAY_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, UNKNOWN_TYPE); // canTestForShallowEqualityWith assertTrue(NUMBER_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertTrue(NUMBER_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(NUMBER_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(NUMBER_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(NUMBER_TYPE.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // isNullable assertFalse(NUMBER_TYPE.isNullable()); // getLeastSupertype assertTypeEquals(ALL_TYPE, NUMBER_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(createUnionType(NUMBER_TYPE, STRING_OBJECT_TYPE), NUMBER_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(NUMBER_TYPE, NUMBER_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(createUnionType(NUMBER_TYPE, functionType), NUMBER_TYPE.getLeastSupertype(functionType)); assertTypeEquals(createUnionType(NUMBER_TYPE, OBJECT_TYPE), NUMBER_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(createUnionType(NUMBER_TYPE, DATE_TYPE), NUMBER_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(createUnionType(NUMBER_TYPE, REGEXP_TYPE), NUMBER_TYPE.getLeastSupertype(REGEXP_TYPE)); // matchesXxx assertTrue(NUMBER_TYPE.matchesInt32Context()); assertTrue(NUMBER_TYPE.matchesNumberContext()); assertTrue(NUMBER_TYPE.matchesObjectContext()); assertTrue(NUMBER_TYPE.matchesStringContext()); assertTrue(NUMBER_TYPE.matchesUint32Context()); // toString assertEquals("number", NUMBER_TYPE.toString()); assertTrue(NUMBER_TYPE.hasDisplayName()); assertEquals("number", NUMBER_TYPE.getDisplayName()); Asserts.assertResolvesToSame(NUMBER_TYPE); assertFalse(NUMBER_TYPE.isNominalConstructor()); } /** * Tests the behavior of the null type. */ public void testNullType() throws Exception { // isXxx assertFalse(NULL_TYPE.isArrayType()); assertFalse(NULL_TYPE.isBooleanValueType()); assertFalse(NULL_TYPE.isDateType()); assertFalse(NULL_TYPE.isEnumElementType()); assertFalse(NULL_TYPE.isNamedType()); assertTrue(NULL_TYPE.isNullType()); assertFalse(NULL_TYPE.isNumber()); assertFalse(NULL_TYPE.isNumberObjectType()); assertFalse(NULL_TYPE.isNumberValueType()); assertFalse(NULL_TYPE.isFunctionPrototypeType()); assertFalse(NULL_TYPE.isRegexpType()); assertFalse(NULL_TYPE.isString()); assertFalse(NULL_TYPE.isStringObjectType()); assertFalse(NULL_TYPE.isStringValueType()); assertFalse(NULL_TYPE.isEnumType()); assertFalse(NULL_TYPE.isUnionType()); assertFalse(NULL_TYPE.isStruct()); assertFalse(NULL_TYPE.isDict()); assertFalse(NULL_TYPE.isAllType()); assertFalse(NULL_TYPE.isVoidType()); assertFalse(NULL_TYPE.isConstructor()); assertFalse(NULL_TYPE.isInstanceType()); // autoboxesTo assertNull(NULL_TYPE.autoboxesTo()); // isSubtype assertFalse(NULL_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(NULL_TYPE.isSubtype(NO_TYPE)); assertTrue(NULL_TYPE.isSubtype(NULL_TYPE)); assertTrue(NULL_TYPE.isSubtype(ALL_TYPE)); assertFalse(NULL_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(NULL_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(NULL_TYPE.isSubtype(functionType)); assertFalse(NULL_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(NULL_TYPE.isSubtype(DATE_TYPE)); assertFalse(NULL_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(NULL_TYPE.isSubtype(ARRAY_TYPE)); assertTrue(NULL_TYPE.isSubtype(UNKNOWN_TYPE)); assertTrue(NULL_TYPE.isSubtype(createNullableType(NO_OBJECT_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(NO_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(NULL_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(ALL_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(STRING_OBJECT_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(NUMBER_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(functionType))); assertTrue(NULL_TYPE.isSubtype(createNullableType(OBJECT_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(DATE_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(REGEXP_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(ARRAY_TYPE))); // canBeCalled assertFalse(NULL_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(NULL_TYPE, NO_TYPE); assertCanTestForEqualityWith(NULL_TYPE, NO_OBJECT_TYPE); assertCanTestForEqualityWith(NULL_TYPE, ALL_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, ARRAY_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, BOOLEAN_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, BOOLEAN_OBJECT_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, DATE_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, ERROR_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, EVAL_ERROR_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, functionType); assertCannotTestForEqualityWith(NULL_TYPE, NULL_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, NUMBER_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, NUMBER_OBJECT_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, OBJECT_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, URI_ERROR_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, RANGE_ERROR_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, REFERENCE_ERROR_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, REGEXP_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, STRING_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, STRING_OBJECT_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, SYNTAX_ERROR_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, TYPE_ERROR_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, VOID_TYPE); // canTestForShallowEqualityWith assertTrue(NULL_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(NULL_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(functionType)); assertTrue(NULL_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(NULL_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(NULL_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(NULL_TYPE.canTestForShallowEqualityWith( createNullableType(STRING_OBJECT_TYPE))); // getLeastSupertype assertTypeEquals(NULL_TYPE, NULL_TYPE.getLeastSupertype(NULL_TYPE)); assertTypeEquals(ALL_TYPE, NULL_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(createNullableType(STRING_OBJECT_TYPE), NULL_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(createNullableType(NUMBER_TYPE), NULL_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(createNullableType(functionType), NULL_TYPE.getLeastSupertype(functionType)); assertTypeEquals(createNullableType(OBJECT_TYPE), NULL_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(createNullableType(DATE_TYPE), NULL_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(createNullableType(REGEXP_TYPE), NULL_TYPE.getLeastSupertype(REGEXP_TYPE)); // matchesXxx assertTrue(NULL_TYPE.matchesInt32Context()); assertTrue(NULL_TYPE.matchesNumberContext()); assertFalse(NULL_TYPE.matchesObjectContext()); assertTrue(NULL_TYPE.matchesStringContext()); assertTrue(NULL_TYPE.matchesUint32Context()); // matchesObjectContext assertFalse(NULL_TYPE.matchesObjectContext()); // toString assertEquals("null", NULL_TYPE.toString()); assertTrue(NULL_TYPE.hasDisplayName()); assertEquals("null", NULL_TYPE.getDisplayName()); Asserts.assertResolvesToSame(NULL_TYPE); // getGreatestSubtype assertTrue( NULL_TYPE.isSubtype( createUnionType(forwardDeclaredNamedType, NULL_TYPE))); assertTypeEquals( createUnionType(forwardDeclaredNamedType, NULL_TYPE), NULL_TYPE.getGreatestSubtype( createUnionType(forwardDeclaredNamedType, NULL_TYPE))); assertFalse(NULL_TYPE.isNominalConstructor()); assertTrue(NULL_TYPE.differsFrom(UNKNOWN_TYPE)); } /** * Tests the behavior of the Date type. */ public void testDateType() throws Exception { // isXxx assertFalse(DATE_TYPE.isArrayType()); assertFalse(DATE_TYPE.isBooleanValueType()); assertTrue(DATE_TYPE.isDateType()); assertFalse(DATE_TYPE.isEnumElementType()); assertFalse(DATE_TYPE.isNamedType()); assertFalse(DATE_TYPE.isNullType()); assertFalse(DATE_TYPE.isNumberValueType()); assertFalse(DATE_TYPE.isFunctionPrototypeType()); assertTrue(DATE_TYPE.getImplicitPrototype().isFunctionPrototypeType()); assertFalse(DATE_TYPE.isRegexpType()); assertFalse(DATE_TYPE.isStringValueType()); assertFalse(DATE_TYPE.isEnumType()); assertFalse(DATE_TYPE.isUnionType()); assertFalse(DATE_TYPE.isStruct()); assertFalse(DATE_TYPE.isDict()); assertFalse(DATE_TYPE.isAllType()); assertFalse(DATE_TYPE.isVoidType()); assertFalse(DATE_TYPE.isConstructor()); assertTrue(DATE_TYPE.isInstanceType()); // autoboxesTo assertNull(DATE_TYPE.autoboxesTo()); // isSubtype assertFalse(DATE_TYPE.isSubtype(NO_TYPE)); assertFalse(DATE_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(DATE_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(DATE_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(DATE_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertTrue(DATE_TYPE.isSubtype(DATE_TYPE)); assertFalse(DATE_TYPE.isSubtype(ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(functionType)); assertFalse(DATE_TYPE.isSubtype(NULL_TYPE)); assertFalse(DATE_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(DATE_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(DATE_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(DATE_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(DATE_TYPE.isSubtype(STRING_TYPE)); assertFalse(DATE_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(DATE_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(DATE_TYPE.isSubtype(ALL_TYPE)); assertFalse(DATE_TYPE.isSubtype(VOID_TYPE)); // canBeCalled assertFalse(DATE_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(DATE_TYPE, ALL_TYPE); assertCanTestForEqualityWith(DATE_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(DATE_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(DATE_TYPE, functionType); assertCannotTestForEqualityWith(DATE_TYPE, VOID_TYPE); assertCanTestForEqualityWith(DATE_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(DATE_TYPE, DATE_TYPE); assertCanTestForEqualityWith(DATE_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(DATE_TYPE, ARRAY_TYPE); // canTestForShallowEqualityWith assertTrue(DATE_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(DATE_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(DATE_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertTrue(DATE_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(DATE_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(DATE_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(DATE_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(DATE_TYPE.isNullable()); assertTrue(createNullableType(DATE_TYPE).isNullable()); // getLeastSupertype assertTypeEquals(ALL_TYPE, DATE_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(createUnionType(DATE_TYPE, STRING_OBJECT_TYPE), DATE_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(createUnionType(DATE_TYPE, NUMBER_TYPE), DATE_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(createUnionType(DATE_TYPE, functionType), DATE_TYPE.getLeastSupertype(functionType)); assertTypeEquals(OBJECT_TYPE, DATE_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(DATE_TYPE, DATE_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(createUnionType(DATE_TYPE, REGEXP_TYPE), DATE_TYPE.getLeastSupertype(REGEXP_TYPE)); // getPropertyType assertEquals(46, DATE_TYPE.getImplicitPrototype().getPropertiesCount()); assertEquals(46, DATE_TYPE.getPropertiesCount()); assertReturnTypeEquals(DATE_TYPE, DATE_TYPE.getPropertyType("constructor")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toString")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toDateString")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toTimeString")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toLocaleString")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toLocaleDateString")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toLocaleTimeString")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("valueOf")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getTime")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getFullYear")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCFullYear")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getMonth")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCMonth")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getDate")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCDate")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getDay")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCDay")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getHours")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCHours")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getMinutes")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCMinutes")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getSeconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCSeconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getMilliseconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCMilliseconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getTimezoneOffset")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setTime")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setMilliseconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCMilliseconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setSeconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCSeconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCSeconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setMinutes")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCMinutes")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setHours")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCHours")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setDate")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCDate")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setMonth")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCMonth")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setFullYear")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCFullYear")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toUTCString")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toGMTString")); // matchesXxx assertTrue(DATE_TYPE.matchesInt32Context()); assertTrue(DATE_TYPE.matchesNumberContext()); assertTrue(DATE_TYPE.matchesObjectContext()); assertTrue(DATE_TYPE.matchesStringContext()); assertTrue(DATE_TYPE.matchesUint32Context()); // toString assertEquals("Date", DATE_TYPE.toString()); assertTrue(DATE_TYPE.hasDisplayName()); assertEquals("Date", DATE_TYPE.getDisplayName()); assertTrue(DATE_TYPE.isNativeObjectType()); Asserts.assertResolvesToSame(DATE_TYPE); assertFalse(DATE_TYPE.isNominalConstructor()); assertTrue(DATE_TYPE.getConstructor().isNominalConstructor()); } /** * Tests the behavior of the RegExp type. */ public void testRegExpType() throws Exception { // isXxx assertFalse(REGEXP_TYPE.isNoType()); assertFalse(REGEXP_TYPE.isNoObjectType()); assertFalse(REGEXP_TYPE.isArrayType()); assertFalse(REGEXP_TYPE.isBooleanValueType()); assertFalse(REGEXP_TYPE.isDateType()); assertFalse(REGEXP_TYPE.isEnumElementType()); assertFalse(REGEXP_TYPE.isNamedType()); assertFalse(REGEXP_TYPE.isNullType()); assertFalse(REGEXP_TYPE.isNumberValueType()); assertFalse(REGEXP_TYPE.isFunctionPrototypeType()); assertTrue(REGEXP_TYPE.getImplicitPrototype().isFunctionPrototypeType()); assertTrue(REGEXP_TYPE.isRegexpType()); assertFalse(REGEXP_TYPE.isStringValueType()); assertFalse(REGEXP_TYPE.isEnumType()); assertFalse(REGEXP_TYPE.isUnionType()); assertFalse(REGEXP_TYPE.isStruct()); assertFalse(REGEXP_TYPE.isDict()); assertFalse(REGEXP_TYPE.isAllType()); assertFalse(REGEXP_TYPE.isVoidType()); // autoboxesTo assertNull(REGEXP_TYPE.autoboxesTo()); // isSubtype assertFalse(REGEXP_TYPE.isSubtype(NO_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(DATE_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(ERROR_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(functionType)); assertFalse(REGEXP_TYPE.isSubtype(NULL_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(REGEXP_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertTrue(REGEXP_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(STRING_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(REGEXP_TYPE.isSubtype(ALL_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(VOID_TYPE)); // canBeCalled assertTrue(REGEXP_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(REGEXP_TYPE, ALL_TYPE); assertCanTestForEqualityWith(REGEXP_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(REGEXP_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(REGEXP_TYPE, functionType); assertCannotTestForEqualityWith(REGEXP_TYPE, VOID_TYPE); assertCanTestForEqualityWith(REGEXP_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(REGEXP_TYPE, DATE_TYPE); assertCanTestForEqualityWith(REGEXP_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(REGEXP_TYPE, ARRAY_TYPE); // canTestForShallowEqualityWith assertTrue(REGEXP_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(REGEXP_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(REGEXP_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(REGEXP_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(REGEXP_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertTrue(REGEXP_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(REGEXP_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(REGEXP_TYPE.isNullable()); assertTrue(createNullableType(REGEXP_TYPE).isNullable()); // getLeastSupertype assertTypeEquals(ALL_TYPE, REGEXP_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(createUnionType(REGEXP_TYPE, STRING_OBJECT_TYPE), REGEXP_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(createUnionType(REGEXP_TYPE, NUMBER_TYPE), REGEXP_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(createUnionType(REGEXP_TYPE, functionType), REGEXP_TYPE.getLeastSupertype(functionType)); assertTypeEquals(OBJECT_TYPE, REGEXP_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(createUnionType(DATE_TYPE, REGEXP_TYPE), REGEXP_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(REGEXP_TYPE, REGEXP_TYPE.getLeastSupertype(REGEXP_TYPE)); // getPropertyType assertEquals(9, REGEXP_TYPE.getImplicitPrototype().getPropertiesCount()); assertEquals(14, REGEXP_TYPE.getPropertiesCount()); assertReturnTypeEquals(REGEXP_TYPE, REGEXP_TYPE.getPropertyType("constructor")); assertReturnTypeEquals(createNullableType(ARRAY_TYPE), REGEXP_TYPE.getPropertyType("exec")); assertReturnTypeEquals(BOOLEAN_TYPE, REGEXP_TYPE.getPropertyType("test")); assertReturnTypeEquals(STRING_TYPE, REGEXP_TYPE.getPropertyType("toString")); assertTypeEquals(STRING_TYPE, REGEXP_TYPE.getPropertyType("source")); assertTypeEquals(BOOLEAN_TYPE, REGEXP_TYPE.getPropertyType("global")); assertTypeEquals(BOOLEAN_TYPE, REGEXP_TYPE.getPropertyType("ignoreCase")); assertTypeEquals(BOOLEAN_TYPE, REGEXP_TYPE.getPropertyType("multiline")); assertTypeEquals(NUMBER_TYPE, REGEXP_TYPE.getPropertyType("lastIndex")); // matchesXxx assertFalse(REGEXP_TYPE.matchesInt32Context()); assertFalse(REGEXP_TYPE.matchesNumberContext()); assertTrue(REGEXP_TYPE.matchesObjectContext()); assertTrue(REGEXP_TYPE.matchesStringContext()); assertFalse(REGEXP_TYPE.matchesUint32Context()); // toString assertEquals("RegExp", REGEXP_TYPE.toString()); assertTrue(REGEXP_TYPE.hasDisplayName()); assertEquals("RegExp", REGEXP_TYPE.getDisplayName()); assertTrue(REGEXP_TYPE.isNativeObjectType()); Asserts.assertResolvesToSame(REGEXP_TYPE); assertFalse(REGEXP_TYPE.isNominalConstructor()); assertTrue(REGEXP_TYPE.getConstructor().isNominalConstructor()); } /** * Tests the behavior of the string object type. */ public void testStringObjectType() throws Exception { // isXxx assertFalse(STRING_OBJECT_TYPE.isArrayType()); assertFalse(STRING_OBJECT_TYPE.isBooleanObjectType()); assertFalse(STRING_OBJECT_TYPE.isBooleanValueType()); assertFalse(STRING_OBJECT_TYPE.isDateType()); assertFalse(STRING_OBJECT_TYPE.isEnumElementType()); assertFalse(STRING_OBJECT_TYPE.isNamedType()); assertFalse(STRING_OBJECT_TYPE.isNullType()); assertFalse(STRING_OBJECT_TYPE.isNumber()); assertFalse(STRING_OBJECT_TYPE.isNumberObjectType()); assertFalse(STRING_OBJECT_TYPE.isNumberValueType()); assertFalse(STRING_OBJECT_TYPE.isFunctionPrototypeType()); assertTrue( STRING_OBJECT_TYPE.getImplicitPrototype().isFunctionPrototypeType()); assertFalse(STRING_OBJECT_TYPE.isRegexpType()); assertTrue(STRING_OBJECT_TYPE.isString()); assertTrue(STRING_OBJECT_TYPE.isStringObjectType()); assertFalse(STRING_OBJECT_TYPE.isStringValueType()); assertFalse(STRING_OBJECT_TYPE.isEnumType()); assertFalse(STRING_OBJECT_TYPE.isUnionType()); assertFalse(STRING_OBJECT_TYPE.isStruct()); assertFalse(STRING_OBJECT_TYPE.isDict()); assertFalse(STRING_OBJECT_TYPE.isAllType()); assertFalse(STRING_OBJECT_TYPE.isVoidType()); assertFalse(STRING_OBJECT_TYPE.isConstructor()); assertTrue(STRING_OBJECT_TYPE.isInstanceType()); // autoboxesTo assertTypeEquals(STRING_OBJECT_TYPE, STRING_TYPE.autoboxesTo()); // unboxesTo assertTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.unboxesTo()); // isSubtype assertTrue(STRING_OBJECT_TYPE.isSubtype(ALL_TYPE)); assertTrue(STRING_OBJECT_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(STRING_OBJECT_TYPE.isSubtype(STRING_TYPE)); assertTrue(STRING_OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(STRING_OBJECT_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(STRING_OBJECT_TYPE.isSubtype(DATE_TYPE)); assertFalse(STRING_OBJECT_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(STRING_OBJECT_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(STRING_OBJECT_TYPE.isSubtype(STRING_TYPE)); // canBeCalled assertFalse(STRING_OBJECT_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(STRING_OBJECT_TYPE, ALL_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, STRING_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, functionType); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, BOOLEAN_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, BOOLEAN_OBJECT_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, DATE_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, ARRAY_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, UNKNOWN_TYPE); // canTestForShallowEqualityWith assertTrue(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertTrue(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // properties (ECMA-262 page 98 - 106) assertEquals(23, STRING_OBJECT_TYPE.getImplicitPrototype(). getPropertiesCount()); assertEquals(24, STRING_OBJECT_TYPE.getPropertiesCount()); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("toString")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("valueOf")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("charAt")); assertReturnTypeEquals(NUMBER_TYPE, STRING_OBJECT_TYPE.getPropertyType("charCodeAt")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("concat")); assertReturnTypeEquals(NUMBER_TYPE, STRING_OBJECT_TYPE.getPropertyType("indexOf")); assertReturnTypeEquals(NUMBER_TYPE, STRING_OBJECT_TYPE.getPropertyType("lastIndexOf")); assertReturnTypeEquals(NUMBER_TYPE, STRING_OBJECT_TYPE.getPropertyType("localeCompare")); assertReturnTypeEquals(createNullableType(ARRAY_TYPE), STRING_OBJECT_TYPE.getPropertyType("match")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("replace")); assertReturnTypeEquals(NUMBER_TYPE, STRING_OBJECT_TYPE.getPropertyType("search")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("slice")); assertReturnTypeEquals(ARRAY_TYPE, STRING_OBJECT_TYPE.getPropertyType("split")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("substring")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("toLowerCase")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("toLocaleLowerCase")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("toUpperCase")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("toLocaleUpperCase")); assertTypeEquals(NUMBER_TYPE, STRING_OBJECT_TYPE.getPropertyType("length")); // matchesXxx assertTrue(STRING_OBJECT_TYPE.matchesInt32Context()); assertTrue(STRING_OBJECT_TYPE.matchesNumberContext()); assertTrue(STRING_OBJECT_TYPE.matchesObjectContext()); assertTrue(STRING_OBJECT_TYPE.matchesStringContext()); assertTrue(STRING_OBJECT_TYPE.matchesUint32Context()); // isNullable assertFalse(STRING_OBJECT_TYPE.isNullable()); assertTrue(createNullableType(STRING_OBJECT_TYPE).isNullable()); assertTrue(STRING_OBJECT_TYPE.isNativeObjectType()); Asserts.assertResolvesToSame(STRING_OBJECT_TYPE); assertTrue(STRING_OBJECT_TYPE.hasDisplayName()); assertEquals("String", STRING_OBJECT_TYPE.getDisplayName()); assertFalse(STRING_OBJECT_TYPE.isNominalConstructor()); assertTrue(STRING_OBJECT_TYPE.getConstructor().isNominalConstructor()); } /** * Tests the behavior of the string value type. */ public void testStringValueType() throws Exception { // isXxx assertFalse(STRING_TYPE.isArrayType()); assertFalse(STRING_TYPE.isBooleanObjectType()); assertFalse(STRING_TYPE.isBooleanValueType()); assertFalse(STRING_TYPE.isDateType()); assertFalse(STRING_TYPE.isEnumElementType()); assertFalse(STRING_TYPE.isNamedType()); assertFalse(STRING_TYPE.isNullType()); assertFalse(STRING_TYPE.isNumber()); assertFalse(STRING_TYPE.isNumberObjectType()); assertFalse(STRING_TYPE.isNumberValueType()); assertFalse(STRING_TYPE.isFunctionPrototypeType()); assertFalse(STRING_TYPE.isRegexpType()); assertTrue(STRING_TYPE.isString()); assertFalse(STRING_TYPE.isStringObjectType()); assertTrue(STRING_TYPE.isStringValueType()); assertFalse(STRING_TYPE.isEnumType()); assertFalse(STRING_TYPE.isUnionType()); assertFalse(STRING_TYPE.isStruct()); assertFalse(STRING_TYPE.isDict()); assertFalse(STRING_TYPE.isAllType()); assertFalse(STRING_TYPE.isVoidType()); assertFalse(STRING_TYPE.isConstructor()); assertFalse(STRING_TYPE.isInstanceType()); // autoboxesTo assertTypeEquals(STRING_OBJECT_TYPE, STRING_TYPE.autoboxesTo()); // unboxesTo assertTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.unboxesTo()); // isSubtype assertTrue(STRING_TYPE.isSubtype(ALL_TYPE)); assertFalse(STRING_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(STRING_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(STRING_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(STRING_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(STRING_TYPE.isSubtype(DATE_TYPE)); assertFalse(STRING_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(STRING_TYPE.isSubtype(ARRAY_TYPE)); assertTrue(STRING_TYPE.isSubtype(STRING_TYPE)); assertTrue(STRING_TYPE.isSubtype(UNKNOWN_TYPE)); // canBeCalled assertFalse(STRING_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(STRING_TYPE, ALL_TYPE); assertCanTestForEqualityWith(STRING_TYPE, STRING_OBJECT_TYPE); assertCannotTestForEqualityWith(STRING_TYPE, functionType); assertCanTestForEqualityWith(STRING_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(STRING_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(STRING_TYPE, BOOLEAN_TYPE); assertCanTestForEqualityWith(STRING_TYPE, BOOLEAN_OBJECT_TYPE); assertCanTestForEqualityWith(STRING_TYPE, DATE_TYPE); assertCanTestForEqualityWith(STRING_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(STRING_TYPE, ARRAY_TYPE); assertCanTestForEqualityWith(STRING_TYPE, UNKNOWN_TYPE); // canTestForShallowEqualityWith assertTrue(STRING_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(STRING_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertTrue(STRING_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(STRING_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(STRING_TYPE.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // matchesXxx assertTrue(STRING_TYPE.matchesInt32Context()); assertTrue(STRING_TYPE.matchesNumberContext()); assertTrue(STRING_TYPE.matchesObjectContext()); assertTrue(STRING_TYPE.matchesStringContext()); assertTrue(STRING_TYPE.matchesUint32Context()); // isNullable assertFalse(STRING_TYPE.isNullable()); assertTrue(createNullableType(STRING_TYPE).isNullable()); // toString assertEquals("string", STRING_TYPE.toString()); assertTrue(STRING_TYPE.hasDisplayName()); assertEquals("string", STRING_TYPE.getDisplayName()); // findPropertyType assertTypeEquals(NUMBER_TYPE, STRING_TYPE.findPropertyType("length")); assertEquals(null, STRING_TYPE.findPropertyType("unknownProperty")); Asserts.assertResolvesToSame(STRING_TYPE); assertFalse(STRING_TYPE.isNominalConstructor()); } private void assertPropertyTypeDeclared(ObjectType ownerType, String prop) { assertTrue(ownerType.isPropertyTypeDeclared(prop)); assertFalse(ownerType.isPropertyTypeInferred(prop)); } private void assertPropertyTypeInferred(ObjectType ownerType, String prop) { assertFalse(ownerType.isPropertyTypeDeclared(prop)); assertTrue(ownerType.isPropertyTypeInferred(prop)); } private void assertPropertyTypeUnknown(ObjectType ownerType, String prop) { assertFalse(ownerType.isPropertyTypeDeclared(prop)); assertFalse(ownerType.isPropertyTypeInferred(prop)); assertTrue(ownerType.getPropertyType(prop).isUnknownType()); } private void assertReturnTypeEquals(JSType expectedReturnType, JSType function) { assertTrue(function instanceof FunctionType); assertTypeEquals(expectedReturnType, ((FunctionType) function).getReturnType()); } /** * Tests the behavior of record types. */ public void testRecordType() throws Exception { // isXxx assertTrue(recordType.isObject()); assertFalse(recordType.isFunctionPrototypeType()); // isSubtype assertTrue(recordType.isSubtype(ALL_TYPE)); assertFalse(recordType.isSubtype(STRING_OBJECT_TYPE)); assertFalse(recordType.isSubtype(NUMBER_TYPE)); assertFalse(recordType.isSubtype(DATE_TYPE)); assertFalse(recordType.isSubtype(REGEXP_TYPE)); assertTrue(recordType.isSubtype(UNKNOWN_TYPE)); assertTrue(recordType.isSubtype(OBJECT_TYPE)); assertFalse(recordType.isSubtype(U2U_CONSTRUCTOR_TYPE)); // autoboxesTo assertNull(recordType.autoboxesTo()); // canBeCalled assertFalse(recordType.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(recordType, ALL_TYPE); assertCanTestForEqualityWith(recordType, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(recordType, recordType); assertCanTestForEqualityWith(recordType, functionType); assertCanTestForEqualityWith(recordType, OBJECT_TYPE); assertCanTestForEqualityWith(recordType, NUMBER_TYPE); assertCanTestForEqualityWith(recordType, DATE_TYPE); assertCanTestForEqualityWith(recordType, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(recordType.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(recordType.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(recordType. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(recordType.canTestForShallowEqualityWith(recordType)); assertFalse(recordType.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(recordType.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(recordType. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(recordType.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(recordType.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // matchesXxx assertFalse(recordType.matchesInt32Context()); assertFalse(recordType.matchesNumberContext()); assertTrue(recordType.matchesObjectContext()); assertFalse(recordType.matchesStringContext()); assertFalse(recordType.matchesUint32Context()); Asserts.assertResolvesToSame(recordType); } /** * Tests the behavior of the instance of Function. */ public void testFunctionInstanceType() throws Exception { FunctionType functionInst = FUNCTION_INSTANCE_TYPE; // isXxx assertTrue(functionInst.isObject()); assertFalse(functionInst.isFunctionPrototypeType()); assertTrue(functionInst.getImplicitPrototype() .isFunctionPrototypeType()); // isSubtype assertTrue(functionInst.isSubtype(ALL_TYPE)); assertFalse(functionInst.isSubtype(STRING_OBJECT_TYPE)); assertFalse(functionInst.isSubtype(NUMBER_TYPE)); assertFalse(functionInst.isSubtype(DATE_TYPE)); assertFalse(functionInst.isSubtype(REGEXP_TYPE)); assertTrue(functionInst.isSubtype(UNKNOWN_TYPE)); assertTrue(functionInst.isSubtype(U2U_CONSTRUCTOR_TYPE)); // autoboxesTo assertNull(functionInst.autoboxesTo()); // canBeCalled assertTrue(functionInst.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(functionInst, ALL_TYPE); assertCanTestForEqualityWith(functionInst, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(functionInst, functionInst); assertCanTestForEqualityWith(functionInst, OBJECT_TYPE); assertCannotTestForEqualityWith(functionInst, NUMBER_TYPE); assertCanTestForEqualityWith(functionInst, DATE_TYPE); assertCanTestForEqualityWith(functionInst, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(functionInst.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(functionInst.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(functionInst. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(functionInst.canTestForShallowEqualityWith(functionInst)); assertFalse(functionInst.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(functionInst.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(functionInst. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(functionInst.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(functionInst.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // matchesXxx assertFalse(functionInst.matchesInt32Context()); assertFalse(functionInst.matchesNumberContext()); assertTrue(functionInst.matchesObjectContext()); assertFalse(functionInst.matchesStringContext()); assertFalse(functionInst.matchesUint32Context()); // hasProperty assertTrue(functionInst.hasProperty("prototype")); assertPropertyTypeInferred(functionInst, "prototype"); // misc assertTypeEquals(FUNCTION_FUNCTION_TYPE, functionInst.getConstructor()); assertTypeEquals(FUNCTION_PROTOTYPE, functionInst.getImplicitPrototype()); assertTypeEquals(functionInst, FUNCTION_FUNCTION_TYPE.getInstanceType()); Asserts.assertResolvesToSame(functionInst); } /** * Tests the behavior of functional types. */ public void testFunctionType() throws Exception { // isXxx assertTrue(functionType.isObject()); assertFalse(functionType.isFunctionPrototypeType()); assertTrue(functionType.getImplicitPrototype().getImplicitPrototype() .isFunctionPrototypeType()); // isSubtype assertTrue(functionType.isSubtype(ALL_TYPE)); assertFalse(functionType.isSubtype(STRING_OBJECT_TYPE)); assertFalse(functionType.isSubtype(NUMBER_TYPE)); assertFalse(functionType.isSubtype(DATE_TYPE)); assertFalse(functionType.isSubtype(REGEXP_TYPE)); assertTrue(functionType.isSubtype(UNKNOWN_TYPE)); assertTrue(functionType.isSubtype(U2U_CONSTRUCTOR_TYPE)); // autoboxesTo assertNull(functionType.autoboxesTo()); // canBeCalled assertTrue(functionType.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(functionType, ALL_TYPE); assertCanTestForEqualityWith(functionType, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(functionType, functionType); assertCanTestForEqualityWith(functionType, OBJECT_TYPE); assertCannotTestForEqualityWith(functionType, NUMBER_TYPE); assertCanTestForEqualityWith(functionType, DATE_TYPE); assertCanTestForEqualityWith(functionType, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(functionType.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(functionType.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(functionType. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(functionType.canTestForShallowEqualityWith(functionType)); assertFalse(functionType.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(functionType.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(functionType. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(functionType.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(functionType.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // matchesXxx assertFalse(functionType.matchesInt32Context()); assertFalse(functionType.matchesNumberContext()); assertTrue(functionType.matchesObjectContext()); assertFalse(functionType.matchesStringContext()); assertFalse(functionType.matchesUint32Context()); // hasProperty assertTrue(functionType.hasProperty("prototype")); assertPropertyTypeInferred(functionType, "prototype"); Asserts.assertResolvesToSame(functionType); assertEquals("aFunctionName", new FunctionBuilder(registry). withName("aFunctionName").build().getDisplayName()); } /** * Tests the subtyping relation of record types. */ public void testRecordTypeSubtyping() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); builder.addProperty("c", STRING_TYPE, null); JSType subRecordType = builder.build(); assertTrue(subRecordType.isSubtype(recordType)); assertFalse(recordType.isSubtype(subRecordType)); builder = new RecordTypeBuilder(registry); builder.addProperty("a", OBJECT_TYPE, null); builder.addProperty("b", STRING_TYPE, null); JSType differentRecordType = builder.build(); assertFalse(differentRecordType.isSubtype(recordType)); assertFalse(recordType.isSubtype(differentRecordType)); } /** * Tests the subtyping relation of record types when an object has * an inferred property.. */ public void testRecordTypeSubtypingWithInferredProperties() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", googSubBarInst, null); JSType record = builder.build(); ObjectType subtypeProp = registry.createAnonymousObjectType(null); subtypeProp.defineInferredProperty("a", googSubSubBarInst, null); assertTrue(subtypeProp.isSubtype(record)); assertFalse(record.isSubtype(subtypeProp)); ObjectType supertypeProp = registry.createAnonymousObjectType(null); supertypeProp.defineInferredProperty("a", googBarInst, null); assertFalse(supertypeProp.isSubtype(record)); assertFalse(record.isSubtype(supertypeProp)); ObjectType declaredSubtypeProp = registry.createAnonymousObjectType(null); declaredSubtypeProp.defineDeclaredProperty("a", googSubSubBarInst, null); assertFalse(declaredSubtypeProp.isSubtype(record)); assertFalse(record.isSubtype(declaredSubtypeProp)); } /** * Tests the getLeastSupertype method for record types. */ public void testRecordTypeLeastSuperType1() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); builder.addProperty("c", STRING_TYPE, null); JSType subRecordType = builder.build(); JSType leastSupertype = recordType.getLeastSupertype(subRecordType); assertTypeEquals(leastSupertype, recordType); } public void testRecordTypeLeastSuperType2() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("e", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); builder.addProperty("c", STRING_TYPE, null); JSType otherRecordType = builder.build(); assertTypeEquals( registry.createUnionType(recordType, otherRecordType), recordType.getLeastSupertype(otherRecordType)); } public void testRecordTypeLeastSuperType3() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("d", NUMBER_TYPE, null); builder.addProperty("e", STRING_TYPE, null); builder.addProperty("f", STRING_TYPE, null); JSType otherRecordType = builder.build(); assertTypeEquals( registry.createUnionType(recordType, otherRecordType), recordType.getLeastSupertype(otherRecordType)); } public void testRecordTypeLeastSuperType4() { JSType leastSupertype = recordType.getLeastSupertype(OBJECT_TYPE); assertTypeEquals(leastSupertype, OBJECT_TYPE); } /** * Tests the getGreatestSubtype method for record types. */ public void testRecordTypeGreatestSubType1() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("d", NUMBER_TYPE, null); builder.addProperty("e", STRING_TYPE, null); builder.addProperty("f", STRING_TYPE, null); JSType subRecordType = builder.build(); JSType subtype = recordType.getGreatestSubtype(subRecordType); builder = new RecordTypeBuilder(registry); builder.addProperty("d", NUMBER_TYPE, null); builder.addProperty("e", STRING_TYPE, null); builder.addProperty("f", STRING_TYPE, null); builder.addProperty("a", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); assertTypeEquals(subtype, builder.build()); } public void testRecordTypeGreatestSubType2() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); JSType subRecordType = builder.build(); JSType subtype = recordType.getGreatestSubtype(subRecordType); builder = new RecordTypeBuilder(registry); builder.addProperty("a", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); assertTypeEquals(subtype, builder.build()); } public void testRecordTypeGreatestSubType3() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); builder.addProperty("c", STRING_TYPE, null); JSType subRecordType = builder.build(); JSType subtype = recordType.getGreatestSubtype(subRecordType); builder = new RecordTypeBuilder(registry); builder.addProperty("a", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); builder.addProperty("c", STRING_TYPE, null); assertTypeEquals(subtype, builder.build()); } public void testRecordTypeGreatestSubType4() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", STRING_TYPE, null); builder.addProperty("b", STRING_TYPE, null); builder.addProperty("c", STRING_TYPE, null); JSType subRecordType = builder.build(); JSType subtype = recordType.getGreatestSubtype(subRecordType); assertTypeEquals(subtype, NO_TYPE); } public void testRecordTypeGreatestSubType5() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", STRING_TYPE, null); JSType recordType = builder.build(); assertTypeEquals(NO_OBJECT_TYPE, recordType.getGreatestSubtype(U2U_CONSTRUCTOR_TYPE)); // if Function is given a property "a" of type "string", then it's // a subtype of the record type {a: string}. U2U_CONSTRUCTOR_TYPE.defineDeclaredProperty("a", STRING_TYPE, null); assertTypeEquals(U2U_CONSTRUCTOR_TYPE, recordType.getGreatestSubtype(U2U_CONSTRUCTOR_TYPE)); assertTypeEquals(U2U_CONSTRUCTOR_TYPE, U2U_CONSTRUCTOR_TYPE.getGreatestSubtype(recordType)); } public void testRecordTypeGreatestSubType6() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("x", UNKNOWN_TYPE, null); JSType recordType = builder.build(); assertTypeEquals(NO_OBJECT_TYPE, recordType.getGreatestSubtype(U2U_CONSTRUCTOR_TYPE)); // if Function is given a property "x" of type "string", then it's // also a subtype of the record type {x: ?}. U2U_CONSTRUCTOR_TYPE.defineDeclaredProperty("x", STRING_TYPE, null); assertTypeEquals(U2U_CONSTRUCTOR_TYPE, recordType.getGreatestSubtype(U2U_CONSTRUCTOR_TYPE)); assertTypeEquals(U2U_CONSTRUCTOR_TYPE, U2U_CONSTRUCTOR_TYPE.getGreatestSubtype(recordType)); } public void testRecordTypeGreatestSubType7() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("x", NUMBER_TYPE, null); JSType recordType = builder.build(); // if Function is given a property "x" of type "string", then it's // not a subtype of the record type {x: number}. U2U_CONSTRUCTOR_TYPE.defineDeclaredProperty("x", STRING_TYPE, null); assertTypeEquals(NO_OBJECT_TYPE, recordType.getGreatestSubtype(U2U_CONSTRUCTOR_TYPE)); } public void testRecordTypeGreatestSubType8() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("xyz", UNKNOWN_TYPE, null); JSType recordType = builder.build(); assertTypeEquals(NO_OBJECT_TYPE, recordType.getGreatestSubtype(U2U_CONSTRUCTOR_TYPE)); // if goog.Bar is given a property "xyz" of type "string", then it's // also a subtype of the record type {x: ?}. googBar.defineDeclaredProperty("xyz", STRING_TYPE, null); assertTypeEquals(googBar, recordType.getGreatestSubtype(U2U_CONSTRUCTOR_TYPE)); assertTypeEquals(googBar, U2U_CONSTRUCTOR_TYPE.getGreatestSubtype(recordType)); ObjectType googBarInst = googBar.getInstanceType(); assertTypeEquals(NO_OBJECT_TYPE, recordType.getGreatestSubtype(googBarInst)); assertTypeEquals(NO_OBJECT_TYPE, googBarInst.getGreatestSubtype(recordType)); } /** * Tests the "apply" method on the function type. */ public void testApplyOfDateMethod() { JSType applyType = dateMethod.getPropertyType("apply"); assertTrue("apply should be a function", applyType instanceof FunctionType); FunctionType applyFn = (FunctionType) applyType; assertTypeEquals("apply should have the same return type as its function", NUMBER_TYPE, applyFn.getReturnType()); Node params = applyFn.getParametersNode(); assertEquals("apply takes two args", 2, params.getChildCount()); assertTypeEquals("apply's first arg is the @this type", registry.createOptionalNullableType(DATE_TYPE), params.getFirstChild().getJSType()); assertTypeEquals("apply's second arg is an Array", registry.createOptionalNullableType(OBJECT_TYPE), params.getLastChild().getJSType()); assertTrue("apply's args must be optional", params.getFirstChild().isOptionalArg()); assertTrue("apply's args must be optional", params.getLastChild().isOptionalArg()); } /** * Tests the "call" method on the function type. */ public void testCallOfDateMethod() { JSType callType = dateMethod.getPropertyType("call"); assertTrue("call should be a function", callType instanceof FunctionType); FunctionType callFn = (FunctionType) callType; assertTypeEquals("call should have the same return type as its function", NUMBER_TYPE, callFn.getReturnType()); Node params = callFn.getParametersNode(); assertEquals("call takes one argument in this case", 1, params.getChildCount()); assertTypeEquals("call's first arg is the @this type", registry.createOptionalNullableType(DATE_TYPE), params.getFirstChild().getJSType()); assertTrue("call's args must be optional", params.getFirstChild().isOptionalArg()); } /** * Tests the representation of function types. */ public void testFunctionTypeRepresentation() { assertEquals("function (number, string): boolean", registry.createFunctionType(BOOLEAN_TYPE, false, NUMBER_TYPE, STRING_TYPE).toString()); assertEquals("function (new:Array, ...[*]): Array", ARRAY_FUNCTION_TYPE.toString()); assertEquals("function (new:Boolean, *=): boolean", BOOLEAN_OBJECT_FUNCTION_TYPE.toString()); assertEquals("function (new:Number, *=): number", NUMBER_OBJECT_FUNCTION_TYPE.toString()); assertEquals("function (new:String, *=): string", STRING_OBJECT_FUNCTION_TYPE.toString()); assertEquals("function (...[number]): boolean", registry.createFunctionType(BOOLEAN_TYPE, true, NUMBER_TYPE) .toString()); assertEquals("function (number, ...[string]): boolean", registry.createFunctionType(BOOLEAN_TYPE, true, NUMBER_TYPE, STRING_TYPE).toString()); assertEquals("function (this:Date, number): (boolean|number|string)", new FunctionBuilder(registry) .withParamsNode(registry.createParameters(NUMBER_TYPE)) .withReturnType(NUMBER_STRING_BOOLEAN) .withTypeOfThis(DATE_TYPE) .build().toString()); } /** * Tests relationships between structural function types. */ public void testFunctionTypeRelationships() { FunctionType dateMethodEmpty = new FunctionBuilder(registry) .withParamsNode(registry.createParameters()) .withTypeOfThis(DATE_TYPE).build(); FunctionType dateMethodWithParam = new FunctionBuilder(registry) .withParamsNode(registry.createOptionalParameters(NUMBER_TYPE)) .withTypeOfThis(DATE_TYPE).build(); FunctionType dateMethodWithReturn = new FunctionBuilder(registry) .withReturnType(NUMBER_TYPE) .withTypeOfThis(DATE_TYPE).build(); FunctionType stringMethodEmpty = new FunctionBuilder(registry) .withParamsNode(registry.createParameters()) .withTypeOfThis(STRING_OBJECT_TYPE).build(); FunctionType stringMethodWithParam = new FunctionBuilder(registry) .withParamsNode(registry.createOptionalParameters(NUMBER_TYPE)) .withTypeOfThis(STRING_OBJECT_TYPE).build(); FunctionType stringMethodWithReturn = new FunctionBuilder(registry) .withReturnType(NUMBER_TYPE) .withTypeOfThis(STRING_OBJECT_TYPE).build(); // One-off tests. assertFalse(stringMethodEmpty.isSubtype(dateMethodEmpty)); // Systemic tests. List<FunctionType> allFunctions = Lists.newArrayList( dateMethodEmpty, dateMethodWithParam, dateMethodWithReturn, stringMethodEmpty, stringMethodWithParam, stringMethodWithReturn); for (int i = 0; i < allFunctions.size(); i++) { for (int j = 0; j < allFunctions.size(); j++) { FunctionType typeA = allFunctions.get(i); FunctionType typeB = allFunctions.get(j); assertEquals(String.format("equals(%s, %s)", typeA, typeB), i == j, typeA.isEquivalentTo(typeB)); // For this particular set of functions, the functions are subtypes // of each other iff they have the same "this" type. assertEquals(String.format("isSubtype(%s, %s)", typeA, typeB), typeA.getTypeOfThis().isEquivalentTo(typeB.getTypeOfThis()), typeA.isSubtype(typeB)); if (i == j) { assertTypeEquals(typeA, typeA.getLeastSupertype(typeB)); assertTypeEquals(typeA, typeA.getGreatestSubtype(typeB)); } else { assertTypeEquals(String.format("sup(%s, %s)", typeA, typeB), U2U_CONSTRUCTOR_TYPE, typeA.getLeastSupertype(typeB)); assertTypeEquals(String.format("inf(%s, %s)", typeA, typeB), LEAST_FUNCTION_TYPE, typeA.getGreatestSubtype(typeB)); } } } } public void testProxiedFunctionTypeRelationships() { FunctionType dateMethodEmpty = new FunctionBuilder(registry) .withParamsNode(registry.createParameters()) .withTypeOfThis(DATE_TYPE).build().toMaybeFunctionType(); FunctionType dateMethodWithParam = new FunctionBuilder(registry) .withParamsNode(registry.createParameters(NUMBER_TYPE)) .withTypeOfThis(DATE_TYPE).build().toMaybeFunctionType(); ProxyObjectType proxyDateMethodEmpty = new ProxyObjectType(registry, dateMethodEmpty); ProxyObjectType proxyDateMethodWithParam = new ProxyObjectType(registry, dateMethodWithParam); assertTypeEquals(U2U_CONSTRUCTOR_TYPE, proxyDateMethodEmpty.getLeastSupertype(proxyDateMethodWithParam)); assertTypeEquals(LEAST_FUNCTION_TYPE, proxyDateMethodEmpty.getGreatestSubtype(proxyDateMethodWithParam)); } /** * Tests relationships between structural function types. */ public void testFunctionSubTypeRelationships() { FunctionType googBarMethod = new FunctionBuilder(registry) .withTypeOfThis(googBar).build(); FunctionType googBarParamFn = new FunctionBuilder(registry) .withParamsNode(registry.createParameters(googBar)).build(); FunctionType googBarReturnFn = new FunctionBuilder(registry) .withParamsNode(registry.createParameters()) .withReturnType(googBar).build(); FunctionType googSubBarMethod = new FunctionBuilder(registry) .withTypeOfThis(googSubBar).build(); FunctionType googSubBarParamFn = new FunctionBuilder(registry) .withParamsNode(registry.createParameters(googSubBar)).build(); FunctionType googSubBarReturnFn = new FunctionBuilder(registry) .withReturnType(googSubBar).build(); assertTrue(googBarMethod.isSubtype(googSubBarMethod)); assertTrue(googBarReturnFn.isSubtype(googSubBarReturnFn)); List<FunctionType> allFunctions = Lists.newArrayList( googBarMethod, googBarParamFn, googBarReturnFn, googSubBarMethod, googSubBarParamFn, googSubBarReturnFn); for (int i = 0; i < allFunctions.size(); i++) { for (int j = 0; j < allFunctions.size(); j++) { FunctionType typeA = allFunctions.get(i); FunctionType typeB = allFunctions.get(j); assertEquals(String.format("equals(%s, %s)", typeA, typeB), i == j, typeA.isEquivalentTo(typeB)); // TODO(nicksantos): This formulation of least subtype and greatest // supertype is a bit loose. We might want to tighten it up later. if (i == j) { assertTypeEquals(typeA, typeA.getLeastSupertype(typeB)); assertTypeEquals(typeA, typeA.getGreatestSubtype(typeB)); } else { assertTypeEquals(String.format("sup(%s, %s)", typeA, typeB), U2U_CONSTRUCTOR_TYPE, typeA.getLeastSupertype(typeB)); assertTypeEquals(String.format("inf(%s, %s)", typeA, typeB), LEAST_FUNCTION_TYPE, typeA.getGreatestSubtype(typeB)); } } } } /** * Tests that defining a property of a function's {@code prototype} adds the * property to it instance type. */ public void testFunctionPrototypeAndImplicitPrototype1() { FunctionType constructor = registry.createConstructorType("Foo", null, null, null, null); ObjectType instance = constructor.getInstanceType(); // adding one property on the prototype ObjectType prototype = (ObjectType) constructor.getPropertyType("prototype"); prototype.defineDeclaredProperty("foo", DATE_TYPE, null); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instance.getPropertiesCount()); } /** * Tests that replacing a function's {@code prototype} changes the visible * properties of its instance type. */ public void testFunctionPrototypeAndImplicitPrototype2() { FunctionType constructor = registry.createConstructorType(null, null, null, null); ObjectType instance = constructor.getInstanceType(); // replacing the prototype ObjectType prototype = registry.createAnonymousObjectType(null); prototype.defineDeclaredProperty("foo", DATE_TYPE, null); constructor.defineDeclaredProperty("prototype", prototype, null); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instance.getPropertiesCount()); } /** Tests assigning JsDoc on a prototype property. */ public void testJSDocOnPrototypeProperty() throws Exception { subclassCtor.setPropertyJSDocInfo("prototype", new JSDocInfo()); assertNull(subclassCtor.getOwnPropertyJSDocInfo("prototype")); } /** * Tests the behavior of the void type. */ public void testVoidType() throws Exception { // isSubtype assertTrue(VOID_TYPE.isSubtype(ALL_TYPE)); assertFalse(VOID_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(VOID_TYPE.isSubtype(REGEXP_TYPE)); // autoboxesTo assertNull(VOID_TYPE.autoboxesTo()); // canTestForEqualityWith assertCanTestForEqualityWith(VOID_TYPE, ALL_TYPE); assertCannotTestForEqualityWith(VOID_TYPE, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(VOID_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(VOID_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertTrue(VOID_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(VOID_TYPE.canTestForShallowEqualityWith( createUnionType(NUMBER_TYPE, VOID_TYPE))); // matchesXxx assertFalse(VOID_TYPE.matchesInt32Context()); assertFalse(VOID_TYPE.matchesNumberContext()); assertFalse(VOID_TYPE.matchesObjectContext()); assertTrue(VOID_TYPE.matchesStringContext()); assertFalse(VOID_TYPE.matchesUint32Context()); Asserts.assertResolvesToSame(VOID_TYPE); } /** * Tests the behavior of the boolean type. */ public void testBooleanValueType() throws Exception { // isXxx assertFalse(BOOLEAN_TYPE.isArrayType()); assertFalse(BOOLEAN_TYPE.isBooleanObjectType()); assertTrue(BOOLEAN_TYPE.isBooleanValueType()); assertFalse(BOOLEAN_TYPE.isDateType()); assertFalse(BOOLEAN_TYPE.isEnumElementType()); assertFalse(BOOLEAN_TYPE.isNamedType()); assertFalse(BOOLEAN_TYPE.isNullType()); assertFalse(BOOLEAN_TYPE.isNumberObjectType()); assertFalse(BOOLEAN_TYPE.isNumberValueType()); assertFalse(BOOLEAN_TYPE.isFunctionPrototypeType()); assertFalse(BOOLEAN_TYPE.isRegexpType()); assertFalse(BOOLEAN_TYPE.isStringObjectType()); assertFalse(BOOLEAN_TYPE.isStringValueType()); assertFalse(BOOLEAN_TYPE.isEnumType()); assertFalse(BOOLEAN_TYPE.isUnionType()); assertFalse(BOOLEAN_TYPE.isStruct()); assertFalse(BOOLEAN_TYPE.isDict()); assertFalse(BOOLEAN_TYPE.isAllType()); assertFalse(BOOLEAN_TYPE.isVoidType()); assertFalse(BOOLEAN_TYPE.isConstructor()); assertFalse(BOOLEAN_TYPE.isInstanceType()); // autoboxesTo assertTypeEquals(BOOLEAN_OBJECT_TYPE, BOOLEAN_TYPE.autoboxesTo()); // unboxesTo assertTypeEquals(BOOLEAN_TYPE, BOOLEAN_OBJECT_TYPE.unboxesTo()); // isSubtype assertTrue(BOOLEAN_TYPE.isSubtype(ALL_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(functionType)); assertFalse(BOOLEAN_TYPE.isSubtype(NULL_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(DATE_TYPE)); assertTrue(BOOLEAN_TYPE.isSubtype(unresolvedNamedType)); assertFalse(BOOLEAN_TYPE.isSubtype(namedGoogBar)); assertFalse(BOOLEAN_TYPE.isSubtype(REGEXP_TYPE)); // canBeCalled assertFalse(BOOLEAN_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(BOOLEAN_TYPE, ALL_TYPE); assertCanTestForEqualityWith(BOOLEAN_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(BOOLEAN_TYPE, NUMBER_TYPE); assertCannotTestForEqualityWith(BOOLEAN_TYPE, functionType); assertCannotTestForEqualityWith(BOOLEAN_TYPE, VOID_TYPE); assertCanTestForEqualityWith(BOOLEAN_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(BOOLEAN_TYPE, DATE_TYPE); assertCanTestForEqualityWith(BOOLEAN_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(BOOLEAN_TYPE, UNKNOWN_TYPE); // canTestForShallowEqualityWith assertTrue(BOOLEAN_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertTrue(BOOLEAN_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(BOOLEAN_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(BOOLEAN_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(BOOLEAN_TYPE.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // isNullable assertFalse(BOOLEAN_TYPE.isNullable()); // matchesXxx assertTrue(BOOLEAN_TYPE.matchesInt32Context()); assertTrue(BOOLEAN_TYPE.matchesNumberContext()); assertTrue(BOOLEAN_TYPE.matchesObjectContext()); assertTrue(BOOLEAN_TYPE.matchesStringContext()); assertTrue(BOOLEAN_TYPE.matchesUint32Context()); // toString assertEquals("boolean", BOOLEAN_TYPE.toString()); assertTrue(BOOLEAN_TYPE.hasDisplayName()); assertEquals("boolean", BOOLEAN_TYPE.getDisplayName()); Asserts.assertResolvesToSame(BOOLEAN_TYPE); } /** * Tests the behavior of the Boolean type. */ public void testBooleanObjectType() throws Exception { // isXxx assertFalse(BOOLEAN_OBJECT_TYPE.isArrayType()); assertTrue(BOOLEAN_OBJECT_TYPE.isBooleanObjectType()); assertFalse(BOOLEAN_OBJECT_TYPE.isBooleanValueType()); assertFalse(BOOLEAN_OBJECT_TYPE.isDateType()); assertFalse(BOOLEAN_OBJECT_TYPE.isEnumElementType()); assertFalse(BOOLEAN_OBJECT_TYPE.isNamedType()); assertFalse(BOOLEAN_OBJECT_TYPE.isNullType()); assertFalse(BOOLEAN_OBJECT_TYPE.isNumberObjectType()); assertFalse(BOOLEAN_OBJECT_TYPE.isNumberValueType()); assertFalse(BOOLEAN_OBJECT_TYPE.isFunctionPrototypeType()); assertTrue( BOOLEAN_OBJECT_TYPE.getImplicitPrototype().isFunctionPrototypeType()); assertFalse(BOOLEAN_OBJECT_TYPE.isRegexpType()); assertFalse(BOOLEAN_OBJECT_TYPE.isStringObjectType()); assertFalse(BOOLEAN_OBJECT_TYPE.isStringValueType()); assertFalse(BOOLEAN_OBJECT_TYPE.isEnumType()); assertFalse(BOOLEAN_OBJECT_TYPE.isUnionType()); assertFalse(BOOLEAN_OBJECT_TYPE.isStruct()); assertFalse(BOOLEAN_OBJECT_TYPE.isDict()); assertFalse(BOOLEAN_OBJECT_TYPE.isAllType()); assertFalse(BOOLEAN_OBJECT_TYPE.isVoidType()); assertFalse(BOOLEAN_OBJECT_TYPE.isConstructor()); assertTrue(BOOLEAN_OBJECT_TYPE.isInstanceType()); // isSubtype assertTrue(BOOLEAN_OBJECT_TYPE.isSubtype(ALL_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(functionType)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(NULL_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(DATE_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE.isSubtype(unresolvedNamedType)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(namedGoogBar)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(REGEXP_TYPE)); // canBeCalled assertFalse(BOOLEAN_OBJECT_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(BOOLEAN_OBJECT_TYPE, ALL_TYPE); assertCanTestForEqualityWith(BOOLEAN_OBJECT_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(BOOLEAN_OBJECT_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(BOOLEAN_OBJECT_TYPE, functionType); assertCannotTestForEqualityWith(BOOLEAN_OBJECT_TYPE, VOID_TYPE); assertCanTestForEqualityWith(BOOLEAN_OBJECT_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(BOOLEAN_OBJECT_TYPE, DATE_TYPE); assertCanTestForEqualityWith(BOOLEAN_OBJECT_TYPE, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(functionType)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(BOOLEAN_OBJECT_TYPE.isNullable()); // matchesXxx assertTrue(BOOLEAN_OBJECT_TYPE.matchesInt32Context()); assertTrue(BOOLEAN_OBJECT_TYPE.matchesNumberContext()); assertTrue(BOOLEAN_OBJECT_TYPE.matchesObjectContext()); assertTrue(BOOLEAN_OBJECT_TYPE.matchesStringContext()); assertTrue(BOOLEAN_OBJECT_TYPE.matchesUint32Context()); // toString assertEquals("Boolean", BOOLEAN_OBJECT_TYPE.toString()); assertTrue(BOOLEAN_OBJECT_TYPE.hasDisplayName()); assertEquals("Boolean", BOOLEAN_OBJECT_TYPE.getDisplayName()); assertTrue(BOOLEAN_OBJECT_TYPE.isNativeObjectType()); Asserts.assertResolvesToSame(BOOLEAN_OBJECT_TYPE); } /** * Tests the behavior of the enum type. */ public void testEnumType() throws Exception { EnumType enumType = new EnumType(registry, "Enum", null, NUMBER_TYPE); // isXxx assertFalse(enumType.isArrayType()); assertFalse(enumType.isBooleanObjectType()); assertFalse(enumType.isBooleanValueType()); assertFalse(enumType.isDateType()); assertFalse(enumType.isEnumElementType()); assertFalse(enumType.isNamedType()); assertFalse(enumType.isNullType()); assertFalse(enumType.isNumberObjectType()); assertFalse(enumType.isNumberValueType()); assertFalse(enumType.isFunctionPrototypeType()); assertFalse(enumType.isRegexpType()); assertFalse(enumType.isStringObjectType()); assertFalse(enumType.isStringValueType()); assertTrue(enumType.isEnumType()); assertFalse(enumType.isUnionType()); assertFalse(enumType.isStruct()); assertFalse(enumType.isDict()); assertFalse(enumType.isAllType()); assertFalse(enumType.isVoidType()); assertFalse(enumType.isConstructor()); assertFalse(enumType.isInstanceType()); // isSubtype assertTrue(enumType.isSubtype(ALL_TYPE)); assertFalse(enumType.isSubtype(STRING_OBJECT_TYPE)); assertFalse(enumType.isSubtype(NUMBER_TYPE)); assertFalse(enumType.isSubtype(functionType)); assertFalse(enumType.isSubtype(NULL_TYPE)); assertTrue(enumType.isSubtype(OBJECT_TYPE)); assertFalse(enumType.isSubtype(DATE_TYPE)); assertTrue(enumType.isSubtype(unresolvedNamedType)); assertFalse(enumType.isSubtype(namedGoogBar)); assertFalse(enumType.isSubtype(REGEXP_TYPE)); // canBeCalled assertFalse(enumType.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(enumType, ALL_TYPE); assertCanTestForEqualityWith(enumType, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(enumType, NUMBER_TYPE); assertCanTestForEqualityWith(enumType, functionType); assertCannotTestForEqualityWith(enumType, VOID_TYPE); assertCanTestForEqualityWith(enumType, OBJECT_TYPE); assertCanTestForEqualityWith(enumType, DATE_TYPE); assertCanTestForEqualityWith(enumType, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(enumType.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(enumType. canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(enumType.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue(enumType. canTestForShallowEqualityWith(enumType)); assertFalse(enumType.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(enumType.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(functionType)); assertFalse(enumType.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(enumType.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(enumType.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(enumType.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(enumType.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(enumType.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(enumType.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(enumType.isNullable()); // matchesXxx assertFalse(enumType.matchesInt32Context()); assertFalse(enumType.matchesNumberContext()); assertTrue(enumType.matchesObjectContext()); assertTrue(enumType.matchesStringContext()); assertFalse(enumType.matchesUint32Context()); // toString assertEquals("enum{Enum}", enumType.toString()); assertTrue(enumType.hasDisplayName()); assertEquals("Enum", enumType.getDisplayName()); assertEquals("AnotherEnum", new EnumType(registry, "AnotherEnum", null, NUMBER_TYPE).getDisplayName()); assertFalse( new EnumType(registry, null, null, NUMBER_TYPE).hasDisplayName()); Asserts.assertResolvesToSame(enumType); } /** * Tests the behavior of the enum element type. */ public void testEnumElementType() throws Exception { // isXxx assertFalse(elementsType.isArrayType()); assertFalse(elementsType.isBooleanObjectType()); assertFalse(elementsType.isBooleanValueType()); assertFalse(elementsType.isDateType()); assertTrue(elementsType.isEnumElementType()); assertFalse(elementsType.isNamedType()); assertFalse(elementsType.isNullType()); assertFalse(elementsType.isNumberObjectType()); assertFalse(elementsType.isNumberValueType()); assertFalse(elementsType.isFunctionPrototypeType()); assertFalse(elementsType.isRegexpType()); assertFalse(elementsType.isStringObjectType()); assertFalse(elementsType.isStringValueType()); assertFalse(elementsType.isEnumType()); assertFalse(elementsType.isUnionType()); assertFalse(elementsType.isStruct()); assertFalse(elementsType.isDict()); assertFalse(elementsType.isAllType()); assertFalse(elementsType.isVoidType()); assertFalse(elementsType.isConstructor()); assertFalse(elementsType.isInstanceType()); // isSubtype assertTrue(elementsType.isSubtype(ALL_TYPE)); assertFalse(elementsType.isSubtype(STRING_OBJECT_TYPE)); assertTrue(elementsType.isSubtype(NUMBER_TYPE)); assertFalse(elementsType.isSubtype(functionType)); assertFalse(elementsType.isSubtype(NULL_TYPE)); assertFalse(elementsType.isSubtype(OBJECT_TYPE)); // no more autoboxing assertFalse(elementsType.isSubtype(DATE_TYPE)); assertTrue(elementsType.isSubtype(unresolvedNamedType)); assertFalse(elementsType.isSubtype(namedGoogBar)); assertFalse(elementsType.isSubtype(REGEXP_TYPE)); // canBeCalled assertFalse(elementsType.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(elementsType, ALL_TYPE); assertCanTestForEqualityWith(elementsType, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(elementsType, NUMBER_TYPE); assertCanTestForEqualityWith(elementsType, NUMBER_OBJECT_TYPE); assertCanTestForEqualityWith(elementsType, elementsType); assertCannotTestForEqualityWith(elementsType, functionType); assertCannotTestForEqualityWith(elementsType, VOID_TYPE); assertCanTestForEqualityWith(elementsType, OBJECT_TYPE); assertCanTestForEqualityWith(elementsType, DATE_TYPE); assertCanTestForEqualityWith(elementsType, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(elementsType.canTestForShallowEqualityWith(NO_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(elementsType.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue(elementsType. canTestForShallowEqualityWith(elementsType)); assertFalse(elementsType.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(elementsType.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(functionType)); assertFalse(elementsType.canTestForShallowEqualityWith(NULL_TYPE)); assertTrue(elementsType.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertFalse(elementsType.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(elementsType.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(elementsType.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(elementsType.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(elementsType.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(elementsType.isNullable()); // matchesXxx assertTrue(elementsType.matchesInt32Context()); assertTrue(elementsType.matchesNumberContext()); assertTrue(elementsType.matchesObjectContext()); assertTrue(elementsType.matchesStringContext()); assertTrue(elementsType.matchesUint32Context()); // toString assertEquals("Enum.<number>", elementsType.toString()); assertTrue(elementsType.hasDisplayName()); assertEquals("Enum", elementsType.getDisplayName()); Asserts.assertResolvesToSame(elementsType); } public void testStringEnumType() throws Exception { EnumElementType stringEnum = new EnumType(registry, "Enum", null, STRING_TYPE).getElementsType(); assertTypeEquals(UNKNOWN_TYPE, stringEnum.getPropertyType("length")); assertTypeEquals(NUMBER_TYPE, stringEnum.findPropertyType("length")); assertEquals(false, stringEnum.hasProperty("length")); assertTypeEquals(STRING_OBJECT_TYPE, stringEnum.autoboxesTo()); assertNull(stringEnum.getConstructor()); Asserts.assertResolvesToSame(stringEnum); } public void testStringObjectEnumType() throws Exception { EnumElementType stringEnum = new EnumType(registry, "Enum", null, STRING_OBJECT_TYPE) .getElementsType(); assertTypeEquals(NUMBER_TYPE, stringEnum.getPropertyType("length")); assertTypeEquals(NUMBER_TYPE, stringEnum.findPropertyType("length")); assertEquals(true, stringEnum.hasProperty("length")); assertTypeEquals(STRING_OBJECT_FUNCTION_TYPE, stringEnum.getConstructor()); } /** * Tests object types. */ public void testObjectType() throws Exception { PrototypeObjectType objectType = new PrototypeObjectType(registry, null, null); // isXxx assertFalse(objectType.isAllType()); assertFalse(objectType.isArrayType()); assertFalse(objectType.isDateType()); assertFalse(objectType.isFunctionPrototypeType()); assertTrue(objectType.getImplicitPrototype() == OBJECT_TYPE); // isSubtype assertTrue(objectType.isSubtype(ALL_TYPE)); assertFalse(objectType.isSubtype(STRING_OBJECT_TYPE)); assertFalse(objectType.isSubtype(NUMBER_TYPE)); assertFalse(objectType.isSubtype(functionType)); assertFalse(objectType.isSubtype(NULL_TYPE)); assertFalse(objectType.isSubtype(DATE_TYPE)); assertTrue(objectType.isSubtype(OBJECT_TYPE)); assertTrue(objectType.isSubtype(unresolvedNamedType)); assertFalse(objectType.isSubtype(namedGoogBar)); assertFalse(objectType.isSubtype(REGEXP_TYPE)); // autoboxesTo assertNull(objectType.autoboxesTo()); // canTestForEqualityWith assertCanTestForEqualityWith(objectType, NUMBER_TYPE); // matchesXxxContext assertFalse(objectType.matchesInt32Context()); assertFalse(objectType.matchesNumberContext()); assertTrue(objectType.matchesObjectContext()); assertFalse(objectType.matchesStringContext()); assertFalse(objectType.matchesUint32Context()); // isNullable assertFalse(objectType.isNullable()); assertTrue(createNullableType(objectType).isNullable()); // toString assertEquals("{...}", objectType.toString()); assertEquals(null, objectType.getDisplayName()); assertFalse(objectType.hasReferenceName()); assertEquals("anObject", new PrototypeObjectType(registry, "anObject", null).getDisplayName()); Asserts.assertResolvesToSame(objectType); } /** * Tests the goog.Bar type. */ public void testGoogBar() throws Exception { assertTrue(namedGoogBar.isInstanceType()); assertFalse(googBar.isInstanceType()); assertFalse(namedGoogBar.isConstructor()); assertTrue(googBar.isConstructor()); assertTrue(googBar.getInstanceType().isInstanceType()); assertTrue(namedGoogBar.getConstructor().isConstructor()); assertTrue(namedGoogBar.getImplicitPrototype().isFunctionPrototypeType()); // isSubtype assertTypeCanAssignToItself(googBar); assertTypeCanAssignToItself(namedGoogBar); googBar.isSubtype(namedGoogBar); namedGoogBar.isSubtype(googBar); assertTypeEquals(googBar, googBar); assertTypeNotEquals(googBar, googSubBar); Asserts.assertResolvesToSame(googBar); Asserts.assertResolvesToSame(googSubBar); } /** * Tests how properties are counted for object types. */ public void testObjectTypePropertiesCount() throws Exception { ObjectType sup = registry.createAnonymousObjectType(null); int nativeProperties = sup.getPropertiesCount(); sup.defineDeclaredProperty("a", DATE_TYPE, null); assertEquals(nativeProperties + 1, sup.getPropertiesCount()); sup.defineDeclaredProperty("b", DATE_TYPE, null); assertEquals(nativeProperties + 2, sup.getPropertiesCount()); ObjectType sub = registry.createObjectType(sup); assertEquals(nativeProperties + 2, sub.getPropertiesCount()); } /** * Tests how properties are defined. */ public void testDefineProperties() { ObjectType prototype = googBar.getPrototype(); ObjectType instance = googBar.getInstanceType(); assertTypeEquals(instance.getImplicitPrototype(), prototype); // Test declarations. assertTrue( prototype.defineDeclaredProperty("declared", NUMBER_TYPE, null)); assertFalse( prototype.defineDeclaredProperty("declared", NUMBER_TYPE, null)); assertFalse( instance.defineDeclaredProperty("declared", NUMBER_TYPE, null)); assertTypeEquals(NUMBER_TYPE, instance.getPropertyType("declared")); // Test inferring different types. assertTrue(prototype.defineInferredProperty("inferred1", STRING_TYPE, null)); assertTrue(prototype.defineInferredProperty("inferred1", NUMBER_TYPE, null)); assertTypeEquals( createUnionType(NUMBER_TYPE, STRING_TYPE), instance.getPropertyType("inferred1")); // Test inferring different types on different objects. assertTrue(prototype.defineInferredProperty("inferred2", STRING_TYPE, null)); assertTrue(instance.defineInferredProperty("inferred2", NUMBER_TYPE, null)); assertTypeEquals( createUnionType(NUMBER_TYPE, STRING_TYPE), instance.getPropertyType("inferred2")); // Test inferring on the supertype and declaring on the subtype. assertTrue( prototype.defineInferredProperty("prop", STRING_TYPE, null)); assertTrue( instance.defineDeclaredProperty("prop", NUMBER_TYPE, null)); assertTypeEquals(NUMBER_TYPE, instance.getPropertyType("prop")); assertTypeEquals(STRING_TYPE, prototype.getPropertyType("prop")); } /** * Tests that properties are correctly counted even when shadowing occurs. */ public void testObjectTypePropertiesCountWithShadowing() { ObjectType sup = registry.createAnonymousObjectType(null); int nativeProperties = sup.getPropertiesCount(); sup.defineDeclaredProperty("a", OBJECT_TYPE, null); assertEquals(nativeProperties + 1, sup.getPropertiesCount()); ObjectType sub = registry.createObjectType(sup); sub.defineDeclaredProperty("a", OBJECT_TYPE, null); assertEquals(nativeProperties + 1, sub.getPropertiesCount()); } /** * Tests the named type goog.Bar. */ public void testNamedGoogBar() throws Exception { // isXxx assertFalse(namedGoogBar.isFunctionPrototypeType()); assertTrue(namedGoogBar.getImplicitPrototype().isFunctionPrototypeType()); // isSubtype assertTrue(namedGoogBar.isSubtype(ALL_TYPE)); assertFalse(namedGoogBar.isSubtype(STRING_OBJECT_TYPE)); assertFalse(namedGoogBar.isSubtype(NUMBER_TYPE)); assertFalse(namedGoogBar.isSubtype(functionType)); assertFalse(namedGoogBar.isSubtype(NULL_TYPE)); assertTrue(namedGoogBar.isSubtype(OBJECT_TYPE)); assertFalse(namedGoogBar.isSubtype(DATE_TYPE)); assertTrue(namedGoogBar.isSubtype(namedGoogBar)); assertTrue(namedGoogBar.isSubtype(unresolvedNamedType)); assertFalse(namedGoogBar.isSubtype(REGEXP_TYPE)); assertFalse(namedGoogBar.isSubtype(ARRAY_TYPE)); // autoboxesTo assertNull(namedGoogBar.autoboxesTo()); // properties assertTypeEquals(DATE_TYPE, namedGoogBar.getPropertyType("date")); assertFalse(namedGoogBar.isNativeObjectType()); assertFalse(namedGoogBar.getImplicitPrototype().isNativeObjectType()); JSType resolvedNamedGoogBar = Asserts.assertValidResolve(namedGoogBar); assertNotSame(resolvedNamedGoogBar, namedGoogBar); assertSame(resolvedNamedGoogBar, googBar.getInstanceType()); } /** * Tests the prototype chaining of native objects. */ public void testPrototypeChaining() throws Exception { // equals assertTypeEquals( ARRAY_TYPE.getImplicitPrototype().getImplicitPrototype(), OBJECT_TYPE); assertTypeEquals( BOOLEAN_OBJECT_TYPE.getImplicitPrototype(). getImplicitPrototype(), OBJECT_TYPE); assertTypeEquals( DATE_TYPE.getImplicitPrototype().getImplicitPrototype(), OBJECT_TYPE); assertTypeEquals( ERROR_TYPE.getImplicitPrototype().getImplicitPrototype(), OBJECT_TYPE); assertTypeEquals( EVAL_ERROR_TYPE.getImplicitPrototype().getImplicitPrototype(), ERROR_TYPE); assertTypeEquals( NUMBER_OBJECT_TYPE.getImplicitPrototype(). getImplicitPrototype(), OBJECT_TYPE); assertTypeEquals( URI_ERROR_TYPE.getImplicitPrototype().getImplicitPrototype(), ERROR_TYPE); assertTypeEquals( RANGE_ERROR_TYPE.getImplicitPrototype().getImplicitPrototype(), ERROR_TYPE); assertTypeEquals( REFERENCE_ERROR_TYPE.getImplicitPrototype(). getImplicitPrototype(), ERROR_TYPE); assertTypeEquals( STRING_OBJECT_TYPE.getImplicitPrototype(). getImplicitPrototype(), OBJECT_TYPE); assertTypeEquals( REGEXP_TYPE.getImplicitPrototype().getImplicitPrototype(), OBJECT_TYPE); assertTypeEquals( SYNTAX_ERROR_TYPE.getImplicitPrototype(). getImplicitPrototype(), ERROR_TYPE); assertTypeEquals( TYPE_ERROR_TYPE.getImplicitPrototype(). getImplicitPrototype(), ERROR_TYPE); // not same assertNotSame(EVAL_ERROR_TYPE.getImplicitPrototype(), URI_ERROR_TYPE.getImplicitPrototype()); assertNotSame(EVAL_ERROR_TYPE.getImplicitPrototype(), RANGE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(EVAL_ERROR_TYPE.getImplicitPrototype(), REFERENCE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(EVAL_ERROR_TYPE.getImplicitPrototype(), SYNTAX_ERROR_TYPE.getImplicitPrototype()); assertNotSame(EVAL_ERROR_TYPE.getImplicitPrototype(), TYPE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(URI_ERROR_TYPE.getImplicitPrototype(), RANGE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(URI_ERROR_TYPE.getImplicitPrototype(), REFERENCE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(URI_ERROR_TYPE.getImplicitPrototype(), SYNTAX_ERROR_TYPE.getImplicitPrototype()); assertNotSame(URI_ERROR_TYPE.getImplicitPrototype(), TYPE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(RANGE_ERROR_TYPE.getImplicitPrototype(), REFERENCE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(RANGE_ERROR_TYPE.getImplicitPrototype(), SYNTAX_ERROR_TYPE.getImplicitPrototype()); assertNotSame(RANGE_ERROR_TYPE.getImplicitPrototype(), TYPE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(REFERENCE_ERROR_TYPE.getImplicitPrototype(), SYNTAX_ERROR_TYPE.getImplicitPrototype()); assertNotSame(REFERENCE_ERROR_TYPE.getImplicitPrototype(), TYPE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(SYNTAX_ERROR_TYPE.getImplicitPrototype(), TYPE_ERROR_TYPE.getImplicitPrototype()); } /** * Tests that function instances have their constructor pointer back at the * function that created them. */ public void testInstanceFunctionChaining() throws Exception { // Array assertTypeEquals( ARRAY_FUNCTION_TYPE, ARRAY_TYPE.getConstructor()); // Boolean assertTypeEquals( BOOLEAN_OBJECT_FUNCTION_TYPE, BOOLEAN_OBJECT_TYPE.getConstructor()); // Date assertTypeEquals( DATE_FUNCTION_TYPE, DATE_TYPE.getConstructor()); // Error assertTypeEquals( ERROR_FUNCTION_TYPE, ERROR_TYPE.getConstructor()); // EvalError assertTypeEquals( EVAL_ERROR_FUNCTION_TYPE, EVAL_ERROR_TYPE.getConstructor()); // Number assertTypeEquals( NUMBER_OBJECT_FUNCTION_TYPE, NUMBER_OBJECT_TYPE.getConstructor()); // Object assertTypeEquals( OBJECT_FUNCTION_TYPE, OBJECT_TYPE.getConstructor()); // RangeError assertTypeEquals( RANGE_ERROR_FUNCTION_TYPE, RANGE_ERROR_TYPE.getConstructor()); // ReferenceError assertTypeEquals( REFERENCE_ERROR_FUNCTION_TYPE, REFERENCE_ERROR_TYPE.getConstructor()); // RegExp assertTypeEquals(REGEXP_FUNCTION_TYPE, REGEXP_TYPE.getConstructor()); // String assertTypeEquals( STRING_OBJECT_FUNCTION_TYPE, STRING_OBJECT_TYPE.getConstructor()); // SyntaxError assertTypeEquals( SYNTAX_ERROR_FUNCTION_TYPE, SYNTAX_ERROR_TYPE.getConstructor()); // TypeError assertTypeEquals( TYPE_ERROR_FUNCTION_TYPE, TYPE_ERROR_TYPE.getConstructor()); // URIError assertTypeEquals( URI_ERROR_FUNCTION_TYPE, URI_ERROR_TYPE.getConstructor()); } /** * Tests that the method {@link JSType#canTestForEqualityWith(JSType)} handles * special corner cases. */ @SuppressWarnings("checked") public void testCanTestForEqualityWithCornerCases() { // null == undefined is always true assertCannotTestForEqualityWith(NULL_TYPE, VOID_TYPE); // (Object,null) == undefined could be true or false UnionType nullableObject = (UnionType) createUnionType(OBJECT_TYPE, NULL_TYPE); assertCanTestForEqualityWith(nullableObject, VOID_TYPE); assertCanTestForEqualityWith(VOID_TYPE, nullableObject); } /** * Tests the {@link JSType#testForEquality(JSType)} method. */ public void testTestForEquality() { compare(TRUE, NO_OBJECT_TYPE, NO_OBJECT_TYPE); compare(UNKNOWN, ALL_TYPE, ALL_TYPE); compare(TRUE, NO_TYPE, NO_TYPE); compare(UNKNOWN, NO_RESOLVED_TYPE, NO_RESOLVED_TYPE); compare(UNKNOWN, NO_OBJECT_TYPE, NUMBER_TYPE); compare(UNKNOWN, ALL_TYPE, NUMBER_TYPE); compare(UNKNOWN, NO_TYPE, NUMBER_TYPE); compare(FALSE, NULL_TYPE, BOOLEAN_TYPE); compare(TRUE, NULL_TYPE, NULL_TYPE); compare(FALSE, NULL_TYPE, NUMBER_TYPE); compare(FALSE, NULL_TYPE, OBJECT_TYPE); compare(FALSE, NULL_TYPE, STRING_TYPE); compare(TRUE, NULL_TYPE, VOID_TYPE); compare(UNKNOWN, NULL_TYPE, createUnionType(UNKNOWN_TYPE, VOID_TYPE)); compare(UNKNOWN, NULL_TYPE, createUnionType(OBJECT_TYPE, VOID_TYPE)); compare(UNKNOWN, NULL_TYPE, unresolvedNamedType); compare(UNKNOWN, NULL_TYPE, createUnionType(unresolvedNamedType, DATE_TYPE)); compare(FALSE, VOID_TYPE, REGEXP_TYPE); compare(TRUE, VOID_TYPE, VOID_TYPE); compare(UNKNOWN, VOID_TYPE, createUnionType(REGEXP_TYPE, VOID_TYPE)); compare(UNKNOWN, NUMBER_TYPE, BOOLEAN_TYPE); compare(UNKNOWN, NUMBER_TYPE, NUMBER_TYPE); compare(UNKNOWN, NUMBER_TYPE, OBJECT_TYPE); compare(UNKNOWN, ARRAY_TYPE, BOOLEAN_TYPE); compare(UNKNOWN, OBJECT_TYPE, BOOLEAN_TYPE); compare(UNKNOWN, OBJECT_TYPE, STRING_TYPE); compare(UNKNOWN, STRING_TYPE, STRING_TYPE); compare(UNKNOWN, STRING_TYPE, BOOLEAN_TYPE); compare(UNKNOWN, STRING_TYPE, NUMBER_TYPE); compare(FALSE, STRING_TYPE, VOID_TYPE); compare(FALSE, STRING_TYPE, NULL_TYPE); compare(FALSE, STRING_TYPE, createUnionType(NULL_TYPE, VOID_TYPE)); compare(UNKNOWN, UNKNOWN_TYPE, BOOLEAN_TYPE); compare(UNKNOWN, UNKNOWN_TYPE, NULL_TYPE); compare(UNKNOWN, UNKNOWN_TYPE, VOID_TYPE); compare(FALSE, U2U_CONSTRUCTOR_TYPE, BOOLEAN_TYPE); compare(FALSE, U2U_CONSTRUCTOR_TYPE, NUMBER_TYPE); compare(FALSE, U2U_CONSTRUCTOR_TYPE, STRING_TYPE); compare(FALSE, U2U_CONSTRUCTOR_TYPE, VOID_TYPE); compare(FALSE, U2U_CONSTRUCTOR_TYPE, NULL_TYPE); compare(UNKNOWN, U2U_CONSTRUCTOR_TYPE, OBJECT_TYPE); compare(UNKNOWN, U2U_CONSTRUCTOR_TYPE, ALL_TYPE); compare(UNKNOWN, NULL_TYPE, subclassOfUnresolvedNamedType); JSType functionAndNull = createUnionType(NULL_TYPE, dateMethod); compare(UNKNOWN, functionAndNull, dateMethod); compare(UNKNOWN, NULL_TYPE, NO_TYPE); compare(UNKNOWN, VOID_TYPE, NO_TYPE); compare(UNKNOWN, NULL_TYPE, unresolvedNamedType); compare(UNKNOWN, VOID_TYPE, unresolvedNamedType); compare(TRUE, NO_TYPE, NO_TYPE); } private void compare(TernaryValue r, JSType t1, JSType t2) { assertEquals(r, t1.testForEquality(t2)); assertEquals(r, t2.testForEquality(t1)); } private void assertCanTestForEqualityWith(JSType t1, JSType t2) { assertTrue(t1.canTestForEqualityWith(t2)); assertTrue(t2.canTestForEqualityWith(t1)); } private void assertCannotTestForEqualityWith(JSType t1, JSType t2) { assertFalse(t1.canTestForEqualityWith(t2)); assertFalse(t2.canTestForEqualityWith(t1)); } /** * Tests the subtyping relationships among simple types. */ public void testSubtypingSimpleTypes() throws Exception { // Any assertTrue(NO_TYPE.isSubtype(NO_TYPE)); assertTrue(NO_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(ARRAY_TYPE)); assertTrue(NO_TYPE.isSubtype(BOOLEAN_TYPE)); assertTrue(NO_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(DATE_TYPE)); assertTrue(NO_TYPE.isSubtype(ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(functionType)); assertTrue(NO_TYPE.isSubtype(NULL_TYPE)); assertTrue(NO_TYPE.isSubtype(NUMBER_TYPE)); assertTrue(NO_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(URI_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(REGEXP_TYPE)); assertTrue(NO_TYPE.isSubtype(STRING_TYPE)); assertTrue(NO_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(ALL_TYPE)); assertTrue(NO_TYPE.isSubtype(VOID_TYPE)); // AnyObject assertFalse(NO_OBJECT_TYPE.isSubtype(NO_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(BOOLEAN_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(DATE_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(functionType)); assertFalse(NO_OBJECT_TYPE.isSubtype(NULL_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(NUMBER_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(URI_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(STRING_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(ALL_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(VOID_TYPE)); // Array assertFalse(ARRAY_TYPE.isSubtype(NO_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(ARRAY_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(DATE_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(ERROR_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(functionType)); assertFalse(ARRAY_TYPE.isSubtype(NULL_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(ARRAY_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(STRING_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(ARRAY_TYPE.isSubtype(ALL_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(VOID_TYPE)); // boolean assertFalse(BOOLEAN_TYPE.isSubtype(NO_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(ARRAY_TYPE)); assertTrue(BOOLEAN_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(DATE_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(functionType)); assertFalse(BOOLEAN_TYPE.isSubtype(NULL_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(STRING_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(BOOLEAN_TYPE.isSubtype(ALL_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(VOID_TYPE)); // Boolean assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(NO_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(BOOLEAN_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(DATE_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(functionType)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(NULL_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(STRING_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE.isSubtype(ALL_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(VOID_TYPE)); // Date assertFalse(DATE_TYPE.isSubtype(NO_TYPE)); assertFalse(DATE_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(DATE_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(DATE_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(DATE_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertTrue(DATE_TYPE.isSubtype(DATE_TYPE)); assertFalse(DATE_TYPE.isSubtype(ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(functionType)); assertFalse(DATE_TYPE.isSubtype(NULL_TYPE)); assertFalse(DATE_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(DATE_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(DATE_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(DATE_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(DATE_TYPE.isSubtype(STRING_TYPE)); assertFalse(DATE_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(DATE_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(DATE_TYPE.isSubtype(ALL_TYPE)); assertFalse(DATE_TYPE.isSubtype(VOID_TYPE)); // Error assertFalse(ERROR_TYPE.isSubtype(NO_TYPE)); assertFalse(ERROR_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(ERROR_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(ERROR_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(ERROR_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(ERROR_TYPE.isSubtype(DATE_TYPE)); assertTrue(ERROR_TYPE.isSubtype(ERROR_TYPE)); assertFalse(ERROR_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(ERROR_TYPE.isSubtype(functionType)); assertFalse(ERROR_TYPE.isSubtype(NULL_TYPE)); assertFalse(ERROR_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(ERROR_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(ERROR_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(ERROR_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(ERROR_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(ERROR_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(ERROR_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(ERROR_TYPE.isSubtype(STRING_TYPE)); assertFalse(ERROR_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(ERROR_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(ERROR_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(ERROR_TYPE.isSubtype(ALL_TYPE)); assertFalse(ERROR_TYPE.isSubtype(VOID_TYPE)); // EvalError assertFalse(EVAL_ERROR_TYPE.isSubtype(NO_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(ERROR_TYPE.isSubtype(DATE_TYPE)); assertTrue(EVAL_ERROR_TYPE.isSubtype(ERROR_TYPE)); assertTrue(EVAL_ERROR_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(functionType)); assertFalse(EVAL_ERROR_TYPE.isSubtype(NULL_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(EVAL_ERROR_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(STRING_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(EVAL_ERROR_TYPE.isSubtype(ALL_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(VOID_TYPE)); // RangeError assertTrue(RANGE_ERROR_TYPE.isSubtype(ERROR_TYPE)); // ReferenceError assertTrue(REFERENCE_ERROR_TYPE.isSubtype(ERROR_TYPE)); // TypeError assertTrue(TYPE_ERROR_TYPE.isSubtype(ERROR_TYPE)); // UriError assertTrue(URI_ERROR_TYPE.isSubtype(ERROR_TYPE)); // Unknown assertFalse(ALL_TYPE.isSubtype(NO_TYPE)); assertFalse(ALL_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(ALL_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(ALL_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(ALL_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(ERROR_TYPE.isSubtype(DATE_TYPE)); assertFalse(ALL_TYPE.isSubtype(ERROR_TYPE)); assertFalse(ALL_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(ALL_TYPE.isSubtype(functionType)); assertFalse(ALL_TYPE.isSubtype(NULL_TYPE)); assertFalse(ALL_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(ALL_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertFalse(ALL_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(ALL_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(ALL_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(ALL_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(ALL_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(ALL_TYPE.isSubtype(STRING_TYPE)); assertFalse(ALL_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(ALL_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(ALL_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(ALL_TYPE.isSubtype(ALL_TYPE)); assertFalse(ALL_TYPE.isSubtype(VOID_TYPE)); } /** * Tests that the Object type is the greatest element (top) of the object * hierarchy. */ public void testSubtypingObjectTopOfObjects() throws Exception { assertTrue(OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertTrue(createUnionType(DATE_TYPE, REGEXP_TYPE).isSubtype(OBJECT_TYPE)); assertTrue(createUnionType(OBJECT_TYPE, NO_OBJECT_TYPE). isSubtype(OBJECT_TYPE)); assertTrue(functionType.isSubtype(OBJECT_TYPE)); } public void testSubtypingFunctionPrototypeType() throws Exception { FunctionType sub1 = registry.createConstructorType(null, null, null, null); sub1.setPrototypeBasedOn(googBar); FunctionType sub2 = registry.createConstructorType(null, null, null, null); sub2.setPrototypeBasedOn(googBar); ObjectType o1 = sub1.getInstanceType(); ObjectType o2 = sub2.getInstanceType(); assertFalse(o1.isSubtype(o2)); assertFalse(o1.getImplicitPrototype().isSubtype(o2.getImplicitPrototype())); assertTrue(o1.getImplicitPrototype().isSubtype(googBar)); assertTrue(o2.getImplicitPrototype().isSubtype(googBar)); } public void testSubtypingFunctionFixedArgs() throws Exception { FunctionType f1 = registry.createFunctionType(OBJECT_TYPE, false, BOOLEAN_TYPE); FunctionType f2 = registry.createFunctionType(STRING_OBJECT_TYPE, false, BOOLEAN_TYPE); assertTrue(f1.isSubtype(f1)); assertFalse(f1.isSubtype(f2)); assertTrue(f2.isSubtype(f1)); assertTrue(f2.isSubtype(f2)); assertTrue(f1.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(f2.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f1)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f2)); } public void testSubtypingFunctionMultipleFixedArgs() throws Exception { FunctionType f1 = registry.createFunctionType(OBJECT_TYPE, false, EVAL_ERROR_TYPE, STRING_TYPE); FunctionType f2 = registry.createFunctionType(STRING_OBJECT_TYPE, false, ERROR_TYPE, ALL_TYPE); assertTrue(f1.isSubtype(f1)); assertFalse(f1.isSubtype(f2)); assertTrue(f2.isSubtype(f1)); assertTrue(f2.isSubtype(f2)); assertTrue(f1.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(f2.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f1)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f2)); } public void testSubtypingFunctionFixedArgsNotMatching() throws Exception { FunctionType f1 = registry.createFunctionType(OBJECT_TYPE, false, EVAL_ERROR_TYPE, UNKNOWN_TYPE); FunctionType f2 = registry.createFunctionType(STRING_OBJECT_TYPE, false, ERROR_TYPE, ALL_TYPE); assertTrue(f1.isSubtype(f1)); assertFalse(f1.isSubtype(f2)); assertTrue(f2.isSubtype(f1)); assertTrue(f2.isSubtype(f2)); assertTrue(f1.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(f2.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f1)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f2)); } public void testSubtypingFunctionVariableArgsOneOnly() throws Exception { // f1 = (EvalError...) -> Object FunctionType f1 = registry.createFunctionType(OBJECT_TYPE, true, EVAL_ERROR_TYPE); // f2 = (Error, Object) -> String FunctionType f2 = registry.createFunctionType(STRING_OBJECT_TYPE, false, ERROR_TYPE, OBJECT_TYPE); assertTrue(f1.isSubtype(f1)); assertFalse(f1.isSubtype(f2)); assertFalse(f2.isSubtype(f1)); assertTrue(f2.isSubtype(f2)); assertTrue(f1.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(f2.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f1)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f2)); } public void testSubtypingFunctionVariableArgsBoth() throws Exception { // f1 = (UriError, EvalError, EvalError...) -> Object FunctionType f1 = registry.createFunctionType(OBJECT_TYPE, true, URI_ERROR_TYPE, EVAL_ERROR_TYPE, EVAL_ERROR_TYPE); // f2 = (Error, Object, EvalError...) -> String FunctionType f2 = registry.createFunctionType(STRING_OBJECT_TYPE, true, ERROR_TYPE, OBJECT_TYPE, EVAL_ERROR_TYPE); assertTrue(f1.isSubtype(f1)); assertFalse(f1.isSubtype(f2)); assertTrue(f2.isSubtype(f1)); assertTrue(f2.isSubtype(f2)); assertTrue(f1.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(f2.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f1)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f2)); } public void testSubtypingMostGeneralFunction() throws Exception { // (EvalError, String) -> Object FunctionType f1 = registry.createFunctionType(OBJECT_TYPE, false, EVAL_ERROR_TYPE, STRING_TYPE); // (string, void) -> number FunctionType f2 = registry.createFunctionType(NUMBER_TYPE, false, STRING_TYPE, VOID_TYPE); // (Date, string, number) -> AnyObject FunctionType f3 = registry.createFunctionType(NO_OBJECT_TYPE, false, DATE_TYPE, STRING_TYPE, NUMBER_TYPE); // (Number) -> Any FunctionType f4 = registry.createFunctionType(NO_TYPE, false, NUMBER_OBJECT_TYPE); // f1 = (EvalError...) -> Object FunctionType f5 = registry.createFunctionType(OBJECT_TYPE, true, EVAL_ERROR_TYPE); // f2 = (Error, Object) -> String FunctionType f6 = registry.createFunctionType(STRING_OBJECT_TYPE, false, ERROR_TYPE, OBJECT_TYPE); // f1 = (UriError, EvalError...) -> Object FunctionType f7 = registry.createFunctionType(OBJECT_TYPE, true, URI_ERROR_TYPE, EVAL_ERROR_TYPE); // f2 = (Error, Object, EvalError...) -> String FunctionType f8 = registry.createFunctionType(STRING_OBJECT_TYPE, true, ERROR_TYPE, OBJECT_TYPE, EVAL_ERROR_TYPE); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(LEAST_FUNCTION_TYPE)); assertTrue(GREATEST_FUNCTION_TYPE.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f1.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f2.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f3.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f4.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f5.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f6.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f7.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f8.isSubtype(GREATEST_FUNCTION_TYPE)); assertFalse(f1.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(f2.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(f3.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(f4.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(f5.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(f6.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(f7.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(f8.isSubtype(LEAST_FUNCTION_TYPE)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f1)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f2)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f3)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f4)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f5)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f6)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f7)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f8)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f1)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f2)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f3)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f4)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f5)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f6)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f7)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f8)); } /** * Types to test for symmetrical relationships. */ private List<JSType> getTypesToTestForSymmetry() { return Lists.newArrayList( UNKNOWN_TYPE, NULL_TYPE, VOID_TYPE, NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE, OBJECT_TYPE, U2U_CONSTRUCTOR_TYPE, LEAST_FUNCTION_TYPE, GREATEST_FUNCTION_TYPE, ALL_TYPE, NO_TYPE, NO_OBJECT_TYPE, NO_RESOLVED_TYPE, createUnionType(BOOLEAN_TYPE, STRING_TYPE), createUnionType(NUMBER_TYPE, STRING_TYPE), createUnionType(NULL_TYPE, dateMethod), createUnionType(UNKNOWN_TYPE, dateMethod), createUnionType(namedGoogBar, dateMethod), createUnionType(NULL_TYPE, unresolvedNamedType), enumType, elementsType, dateMethod, functionType, unresolvedNamedType, googBar, namedGoogBar, googBar.getInstanceType(), namedGoogBar, subclassOfUnresolvedNamedType, subclassCtor, recordType, forwardDeclaredNamedType, createUnionType(forwardDeclaredNamedType, NULL_TYPE), createTemplatizedType(OBJECT_TYPE, STRING_TYPE), createTemplatizedType(OBJECT_TYPE, NUMBER_TYPE), createTemplatizedType(ARRAY_TYPE, STRING_TYPE), createTemplatizedType(ARRAY_TYPE, NUMBER_TYPE), createUnionType( createTemplatizedType(ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), createUnionType( createTemplatizedType(OBJECT_TYPE, BOOLEAN_TYPE), NULL_TYPE) ); } public void testSymmetryOfTestForEquality() { List<JSType> listA = getTypesToTestForSymmetry(); List<JSType> listB = getTypesToTestForSymmetry(); for (JSType typeA : listA) { for (JSType typeB : listB) { TernaryValue aOnB = typeA.testForEquality(typeB); TernaryValue bOnA = typeB.testForEquality(typeA); assertTrue( String.format("testForEquality not symmetrical:\n" + "typeA: %s\ntypeB: %s\n" + "a.testForEquality(b): %s\n" + "b.testForEquality(a): %s\n", typeA, typeB, aOnB, bOnA), aOnB == bOnA); } } } /** * Tests that getLeastSupertype is a symmetric relation. */ public void testSymmetryOfLeastSupertype() { List<JSType> listA = getTypesToTestForSymmetry(); List<JSType> listB = getTypesToTestForSymmetry(); for (JSType typeA : listA) { for (JSType typeB : listB) { JSType aOnB = typeA.getLeastSupertype(typeB); JSType bOnA = typeB.getLeastSupertype(typeA); // Use a custom assert message instead of the normal assertTypeEquals, // to make it more helpful. assertTrue( String.format("getLeastSupertype not symmetrical:\n" + "typeA: %s\ntypeB: %s\n" + "a.getLeastSupertype(b): %s\n" + "b.getLeastSupertype(a): %s\n", typeA, typeB, aOnB, bOnA), aOnB.isEquivalentTo(bOnA)); } } } public void testWeirdBug() { assertTypeNotEquals(googBar, googBar.getInstanceType()); assertFalse(googBar.isSubtype(googBar.getInstanceType())); assertFalse(googBar.getInstanceType().isSubtype(googBar)); } /** * Tests that getGreatestSubtype is a symmetric relation. */ public void testSymmetryOfGreatestSubtype() { List<JSType> listA = getTypesToTestForSymmetry(); List<JSType> listB = getTypesToTestForSymmetry(); for (JSType typeA : listA) { for (JSType typeB : listB) { JSType aOnB = typeA.getGreatestSubtype(typeB); JSType bOnA = typeB.getGreatestSubtype(typeA); // Use a custom assert message instead of the normal assertTypeEquals, // to make it more helpful. assertTrue( String.format("getGreatestSubtype not symmetrical:\n" + "typeA: %s\ntypeB: %s\n" + "a.getGreatestSubtype(b): %s\n" + "b.getGreatestSubtype(a): %s\n", typeA, typeB, aOnB, bOnA), aOnB.isEquivalentTo(bOnA)); } } } /** * Tests that getLeastSupertype is a reflexive relation. */ public void testReflexivityOfLeastSupertype() { List<JSType> list = getTypesToTestForSymmetry(); for (JSType type : list) { assertTypeEquals("getLeastSupertype not reflexive", type, type.getLeastSupertype(type)); } } /** * Tests that getGreatestSubtype is a reflexive relation. */ public void testReflexivityOfGreatestSubtype() { List<JSType> list = getTypesToTestForSymmetry(); for (JSType type : list) { assertTypeEquals("getGreatestSubtype not reflexive", type, type.getGreatestSubtype(type)); } } /** * Tests {@link JSType#getLeastSupertype(JSType)} for unresolved named types. */ public void testLeastSupertypeUnresolvedNamedType() { // (undefined,function(?):?) and ? unresolved named type JSType expected = registry.createUnionType( unresolvedNamedType, U2U_FUNCTION_TYPE); assertTypeEquals(expected, unresolvedNamedType.getLeastSupertype(U2U_FUNCTION_TYPE)); assertTypeEquals(expected, U2U_FUNCTION_TYPE.getLeastSupertype(unresolvedNamedType)); assertEquals("(function (...[?]): ?|not.resolved.named.type)", expected.toString()); } public void testLeastSupertypeUnresolvedNamedType2() { JSType expected = registry.createUnionType( unresolvedNamedType, UNKNOWN_TYPE); assertTypeEquals(expected, unresolvedNamedType.getLeastSupertype(UNKNOWN_TYPE)); assertTypeEquals(expected, UNKNOWN_TYPE.getLeastSupertype(unresolvedNamedType)); assertTypeEquals(UNKNOWN_TYPE, expected); } public void testLeastSupertypeUnresolvedNamedType3() { JSType expected = registry.createUnionType( unresolvedNamedType, CHECKED_UNKNOWN_TYPE); assertTypeEquals(expected, unresolvedNamedType.getLeastSupertype(CHECKED_UNKNOWN_TYPE)); assertTypeEquals(expected, CHECKED_UNKNOWN_TYPE.getLeastSupertype(unresolvedNamedType)); assertTypeEquals(CHECKED_UNKNOWN_TYPE, expected); } /** Tests the subclass of an unresolved named type */ public void testSubclassOfUnresolvedNamedType() { assertTrue(subclassOfUnresolvedNamedType.isUnknownType()); } /** * Tests that Proxied FunctionTypes behave the same over getLeastSupertype and * getGreatestSubtype as non proxied FunctionTypes */ public void testSupertypeOfProxiedFunctionTypes() { ObjectType fn1 = new FunctionBuilder(registry) .withParamsNode(new Node(Token.PARAM_LIST)) .withReturnType(NUMBER_TYPE) .build(); ObjectType fn2 = new FunctionBuilder(registry) .withParamsNode(new Node(Token.PARAM_LIST)) .withReturnType(STRING_TYPE) .build(); ObjectType p1 = new ProxyObjectType(registry, fn1); ObjectType p2 = new ProxyObjectType(registry, fn2); ObjectType supremum = new FunctionBuilder(registry) .withParamsNode(new Node(Token.PARAM_LIST)) .withReturnType(registry.createUnionType(STRING_TYPE, NUMBER_TYPE)) .build(); assertTypeEquals(fn1.getLeastSupertype(fn2), p1.getLeastSupertype(p2)); assertTypeEquals(supremum, fn1.getLeastSupertype(fn2)); assertTypeEquals(supremum, fn1.getLeastSupertype(p2)); assertTypeEquals(supremum, p1.getLeastSupertype(fn2)); assertTypeEquals(supremum, p1.getLeastSupertype(p2)); } public void testTypeOfThisIsProxied() { ObjectType fnType = new FunctionBuilder(registry) .withReturnType(NUMBER_TYPE).withTypeOfThis(OBJECT_TYPE).build(); ObjectType proxyType = new ProxyObjectType(registry, fnType); assertTypeEquals(fnType.getTypeOfThis(), proxyType.getTypeOfThis()); } /** * Tests the {@link NamedType#equals} function, which had a bug in it. */ public void testNamedTypeEquals() { JSTypeRegistry jst = new JSTypeRegistry(null); // test == if references are equal NamedType a = new NamedType(jst, "type1", "source", 1, 0); NamedType b = new NamedType(jst, "type1", "source", 1, 0); assertTrue(a.isEquivalentTo(b)); // test == instance of referenced type assertTrue(namedGoogBar.isEquivalentTo(googBar.getInstanceType())); assertTrue(googBar.getInstanceType().isEquivalentTo(namedGoogBar)); } /** * Tests the {@link NamedType#equals} function against other types. */ public void testNamedTypeEquals2() { // test == if references are equal NamedType a = new NamedType(registry, "typeA", "source", 1, 0); NamedType b = new NamedType(registry, "typeB", "source", 1, 0); ObjectType realA = registry.createConstructorType( "typeA", null, null, null, null).getInstanceType(); ObjectType realB = registry.createEnumType( "typeB", null, NUMBER_TYPE).getElementsType(); registry.declareType("typeA", realA); registry.declareType("typeB", realB); assertTypeEquals(a, realA); assertTypeEquals(b, realB); a.resolve(null, null); b.resolve(null, null); assertTrue(a.isResolved()); assertTrue(b.isResolved()); assertTypeEquals(a, realA); assertTypeEquals(b, realB); JSType resolvedA = Asserts.assertValidResolve(a); assertNotSame(resolvedA, a); assertSame(resolvedA, realA); JSType resolvedB = Asserts.assertValidResolve(b); assertNotSame(resolvedB, b); assertSame(resolvedB, realB); } /** * Tests the {@link NamedType#equals} function against other types * when it's forward-declared. */ public void testForwardDeclaredNamedTypeEquals() { // test == if references are equal NamedType a = new NamedType(registry, "typeA", "source", 1, 0); NamedType b = new NamedType(registry, "typeA", "source", 1, 0); registry.forwardDeclareType("typeA"); assertTypeEquals(a, b); a.resolve(null, EMPTY_SCOPE); assertTrue(a.isResolved()); assertFalse(b.isResolved()); assertTypeEquals(a, b); assertFalse(a.isEquivalentTo(UNKNOWN_TYPE)); assertFalse(b.isEquivalentTo(UNKNOWN_TYPE)); assertTrue(a.isEmptyType()); assertFalse(a.isNoType()); assertTrue(a.isNoResolvedType()); } public void testForwardDeclaredNamedType() { NamedType a = new NamedType(registry, "typeA", "source", 1, 0); registry.forwardDeclareType("typeA"); assertTypeEquals(UNKNOWN_TYPE, a.getLeastSupertype(UNKNOWN_TYPE)); assertTypeEquals(CHECKED_UNKNOWN_TYPE, a.getLeastSupertype(CHECKED_UNKNOWN_TYPE)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(a)); assertTypeEquals(CHECKED_UNKNOWN_TYPE, CHECKED_UNKNOWN_TYPE.getLeastSupertype(a)); } /** * Tests {@link JSType#getGreatestSubtype(JSType)} on simple types. */ public void testGreatestSubtypeSimpleTypes() { assertTypeEquals(ARRAY_TYPE, ARRAY_TYPE.getGreatestSubtype(ALL_TYPE)); assertTypeEquals(ARRAY_TYPE, ALL_TYPE.getGreatestSubtype(ARRAY_TYPE)); assertTypeEquals(NO_OBJECT_TYPE, REGEXP_TYPE.getGreatestSubtype(NO_OBJECT_TYPE)); assertTypeEquals(NO_OBJECT_TYPE, NO_OBJECT_TYPE.getGreatestSubtype(REGEXP_TYPE)); assertTypeEquals(NO_OBJECT_TYPE, ARRAY_TYPE.getGreatestSubtype(STRING_OBJECT_TYPE)); assertTypeEquals(NO_TYPE, ARRAY_TYPE.getGreatestSubtype(NUMBER_TYPE)); assertTypeEquals(NO_OBJECT_TYPE, ARRAY_TYPE.getGreatestSubtype(functionType)); assertTypeEquals(STRING_OBJECT_TYPE, STRING_OBJECT_TYPE.getGreatestSubtype(OBJECT_TYPE)); assertTypeEquals(STRING_OBJECT_TYPE, OBJECT_TYPE.getGreatestSubtype(STRING_OBJECT_TYPE)); assertTypeEquals(NO_OBJECT_TYPE, ARRAY_TYPE.getGreatestSubtype(DATE_TYPE)); assertTypeEquals(NO_OBJECT_TYPE, ARRAY_TYPE.getGreatestSubtype(REGEXP_TYPE)); assertTypeEquals(EVAL_ERROR_TYPE, ERROR_TYPE.getGreatestSubtype(EVAL_ERROR_TYPE)); assertTypeEquals(EVAL_ERROR_TYPE, EVAL_ERROR_TYPE.getGreatestSubtype(ERROR_TYPE)); assertTypeEquals(NO_TYPE, NULL_TYPE.getGreatestSubtype(ERROR_TYPE)); assertTypeEquals(UNKNOWN_TYPE, NUMBER_TYPE.getGreatestSubtype(UNKNOWN_TYPE)); assertTypeEquals(NO_RESOLVED_TYPE, NO_OBJECT_TYPE.getGreatestSubtype(forwardDeclaredNamedType)); assertTypeEquals(NO_RESOLVED_TYPE, forwardDeclaredNamedType.getGreatestSubtype(NO_OBJECT_TYPE)); } /** * Tests that a derived class extending a type via a named type is a subtype * of it. */ public void testSubtypingDerivedExtendsNamedBaseType() throws Exception { ObjectType derived = registry.createObjectType(registry.createObjectType(namedGoogBar)); assertTrue(derived.isSubtype(googBar.getInstanceType())); } public void testNamedSubtypeChain() throws Exception { List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_PROTOTYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), googBar.getPrototype(), googBar.getInstanceType(), googSubBar.getPrototype(), googSubBar.getInstanceType(), googSubSubBar.getPrototype(), googSubSubBar.getInstanceType(), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testRecordSubtypeChain() throws Exception { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", STRING_TYPE, null); JSType aType = builder.build(); builder = new RecordTypeBuilder(registry); builder.addProperty("a", STRING_TYPE, null); builder.addProperty("b", STRING_TYPE, null); JSType abType = builder.build(); builder = new RecordTypeBuilder(registry); builder.addProperty("a", STRING_TYPE, null); builder.addProperty("c", STRING_TYPE, null); JSType acType = builder.build(); JSType abOrAcType = registry.createUnionType(abType, acType); builder = new RecordTypeBuilder(registry); builder.addProperty("a", STRING_TYPE, null); builder.addProperty("b", STRING_TYPE, null); builder.addProperty("c", NUMBER_TYPE, null); JSType abcType = builder.build(); List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_PROTOTYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), aType, abOrAcType, abType, abcType, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testRecordAndObjectChain2() throws Exception { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("date", DATE_TYPE, null); JSType hasDateProperty = builder.build(); List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.OBJECT_TYPE), hasDateProperty, googBar.getInstanceType(), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testRecordAndObjectChain3() throws Exception { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("date", UNKNOWN_TYPE, null); JSType hasUnknownDateProperty = builder.build(); List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.OBJECT_TYPE), hasUnknownDateProperty, googBar.getInstanceType(), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testNullableNamedTypeChain() throws Exception { List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.createOptionalNullableType( registry.getNativeType(JSTypeNative.OBJECT_PROTOTYPE)), registry.createOptionalNullableType( registry.getNativeType(JSTypeNative.OBJECT_TYPE)), registry.createOptionalNullableType(googBar.getPrototype()), registry.createOptionalNullableType(googBar.getInstanceType()), registry.createNullableType(googSubBar.getPrototype()), registry.createNullableType(googSubBar.getInstanceType()), googSubSubBar.getPrototype(), googSubSubBar.getInstanceType(), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testEnumTypeChain() throws Exception { List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_PROTOTYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), enumType, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testFunctionSubtypeChain() throws Exception { List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_PROTOTYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), registry.getNativeType(JSTypeNative.FUNCTION_PROTOTYPE), registry.getNativeType(JSTypeNative.GREATEST_FUNCTION_TYPE), dateMethod, registry.getNativeType(JSTypeNative.LEAST_FUNCTION_TYPE), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testFunctionUnionSubtypeChain() throws Exception { List<JSType> typeChain = Lists.newArrayList( createUnionType( OBJECT_TYPE, STRING_TYPE), createUnionType( GREATEST_FUNCTION_TYPE, googBarInst, STRING_TYPE), createUnionType( STRING_TYPE, registry.createFunctionType( createUnionType(STRING_TYPE, NUMBER_TYPE)), googBarInst), createUnionType( registry.createFunctionType(NUMBER_TYPE), googSubBarInst), LEAST_FUNCTION_TYPE, NO_OBJECT_TYPE, NO_TYPE); verifySubtypeChain(typeChain); } public void testConstructorSubtypeChain() throws Exception { List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_PROTOTYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), registry.getNativeType(JSTypeNative.FUNCTION_PROTOTYPE), registry.getNativeType(JSTypeNative.FUNCTION_INSTANCE_TYPE), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testGoogBarSubtypeChain() throws Exception { List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.FUNCTION_INSTANCE_TYPE), googBar, googSubBar, googSubSubBar, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE)); verifySubtypeChain(typeChain, false); } public void testConstructorWithArgSubtypeChain() throws Exception { FunctionType googBarArgConstructor = registry.createConstructorType( "barArg", null, registry.createParameters(googBar), null, null); FunctionType googSubBarArgConstructor = registry.createConstructorType( "subBarArg", null, registry.createParameters(googSubBar), null, null); List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.FUNCTION_INSTANCE_TYPE), googBarArgConstructor, googSubBarArgConstructor, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE)); verifySubtypeChain(typeChain, false); } public void testInterfaceInstanceSubtypeChain() throws Exception { List<JSType> typeChain = Lists.newArrayList( ALL_TYPE, OBJECT_TYPE, interfaceInstType, googBar.getPrototype(), googBarInst, googSubBar.getPrototype(), googSubBarInst, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testInterfaceInheritanceSubtypeChain() throws Exception { FunctionType tempType = registry.createConstructorType("goog.TempType", null, null, null, null); tempType.setImplementedInterfaces( Lists.<ObjectType>newArrayList(subInterfaceInstType)); List<JSType> typeChain = Lists.newArrayList( ALL_TYPE, OBJECT_TYPE, interfaceInstType, subInterfaceInstType, tempType.getPrototype(), tempType.getInstanceType(), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testAnonymousObjectChain() throws Exception { List<JSType> typeChain = Lists.newArrayList( ALL_TYPE, createNullableType(OBJECT_TYPE), OBJECT_TYPE, registry.createAnonymousObjectType(null), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testAnonymousEnumElementChain() throws Exception { ObjectType enumElemType = registry.createEnumType( "typeB", null, registry.createAnonymousObjectType(null)).getElementsType(); List<JSType> typeChain = Lists.newArrayList( ALL_TYPE, createNullableType(OBJECT_TYPE), OBJECT_TYPE, enumElemType, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testTemplatizedArrayChain() throws Exception { JSType arrayOfNoType = createTemplatizedType( ARRAY_TYPE, NO_TYPE); JSType arrayOfString = createTemplatizedType( ARRAY_TYPE, STRING_TYPE); JSType arrayOfStringOrNumber = createTemplatizedType( ARRAY_TYPE, createUnionType(STRING_TYPE, NUMBER_TYPE)); JSType arrayOfAllType = createTemplatizedType( ARRAY_TYPE, ALL_TYPE); List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), arrayOfAllType, arrayOfStringOrNumber, arrayOfString, arrayOfNoType, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain, false); } public void testTemplatizedArrayChain2() throws Exception { JSType arrayOfNoType = createTemplatizedType( ARRAY_TYPE, NO_TYPE); JSType arrayOfNoObjectType = createTemplatizedType( ARRAY_TYPE, NO_OBJECT_TYPE); JSType arrayOfArray = createTemplatizedType( ARRAY_TYPE, ARRAY_TYPE); JSType arrayOfObject = createTemplatizedType( ARRAY_TYPE, OBJECT_TYPE); JSType arrayOfAllType = createTemplatizedType( ARRAY_TYPE, ALL_TYPE); List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), arrayOfAllType, arrayOfObject, arrayOfArray, arrayOfNoObjectType, arrayOfNoType, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain, false); } public void testTemplatizedObjectChain() throws Exception { JSType objectOfNoType = createTemplatizedType( OBJECT_TYPE, NO_TYPE); JSType objectOfString = createTemplatizedType( OBJECT_TYPE, STRING_TYPE); JSType objectOfStringOrNumber = createTemplatizedType( OBJECT_TYPE, createUnionType(STRING_TYPE, NUMBER_TYPE)); JSType objectOfAllType = createTemplatizedType( OBJECT_TYPE, ALL_TYPE); List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), objectOfAllType, objectOfStringOrNumber, objectOfString, objectOfNoType, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain, false); } public void testMixedTemplatizedTypeChain() throws Exception { JSType arrayOfNoType = createTemplatizedType( ARRAY_TYPE, NO_TYPE); JSType arrayOfString = createTemplatizedType( ARRAY_TYPE, STRING_TYPE); JSType objectOfString = createTemplatizedType( OBJECT_TYPE, STRING_TYPE); JSType objectOfStringOrNumber = createTemplatizedType( OBJECT_TYPE, createUnionType(STRING_TYPE, NUMBER_TYPE)); JSType objectOfAllType = createTemplatizedType( OBJECT_TYPE, ALL_TYPE); List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), objectOfAllType, objectOfStringOrNumber, objectOfString, arrayOfString, arrayOfNoType, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain, false); } public void testTemplatizedTypeSubtypes() { JSType objectOfString = createTemplatizedType( OBJECT_TYPE, STRING_TYPE); JSType arrayOfString = createTemplatizedType( ARRAY_TYPE, STRING_TYPE); JSType arrayOfNumber = createTemplatizedType( ARRAY_TYPE, NUMBER_TYPE); JSType arrayOfUnknown = createTemplatizedType( ARRAY_TYPE, UNKNOWN_TYPE); assertFalse(objectOfString.isSubtype(ARRAY_TYPE)); // TODO(johnlenz): should this be false? assertTrue(ARRAY_TYPE.isSubtype(objectOfString)); assertFalse(objectOfString.isSubtype(ARRAY_TYPE)); // TODO(johnlenz): should this be false? assertTrue(ARRAY_TYPE.isSubtype(objectOfString)); assertTrue(arrayOfString.isSubtype(ARRAY_TYPE)); assertTrue(ARRAY_TYPE.isSubtype(arrayOfString)); assertTrue(arrayOfString.isSubtype(arrayOfUnknown)); assertTrue(arrayOfUnknown.isSubtype(arrayOfString)); assertFalse(arrayOfString.isSubtype(arrayOfNumber)); assertFalse(arrayOfNumber.isSubtype(arrayOfString)); assertTrue(arrayOfNumber.isSubtype(createUnionType(arrayOfNumber, NULL_VOID))); assertFalse(createUnionType(arrayOfNumber, NULL_VOID).isSubtype(arrayOfNumber)); assertFalse(arrayOfString.isSubtype(createUnionType(arrayOfNumber, NULL_VOID))); } public void testTemplatizedTypeRelations() throws Exception { JSType objectOfString = createTemplatizedType( OBJECT_TYPE, STRING_TYPE); JSType arrayOfString = createTemplatizedType( ARRAY_TYPE, STRING_TYPE); JSType arrayOfNumber = createTemplatizedType( ARRAY_TYPE, NUMBER_TYPE); // Union and least super type cases: // // 1) alternate:Array.<string> and current:Object ==> Object // 2) alternate:Array.<string> and current:Array ==> Array // 3) alternate:Object.<string> and current:Array ==> Array|Object.<string> // 4) alternate:Object and current:Array.<string> ==> Object // 5) alternate:Array and current:Array.<string> ==> Array // 6) alternate:Array and current:Object.<string> ==> Array|Object.<string> // 7) alternate:Array.<string> and current:Array.<number> ==> Array.<?> // 8) alternate:Array.<string> and current:Array.<string> ==> Array.<string> // 9) alternate:Array.<string> and // current:Object.<string> ==> Object.<string>|Array.<string> assertTypeEquals( OBJECT_TYPE, JSType.getLeastSupertype(arrayOfString, OBJECT_TYPE)); assertTypeEquals( OBJECT_TYPE, JSType.getLeastSupertype(OBJECT_TYPE, arrayOfString)); assertTypeEquals( ARRAY_TYPE, JSType.getLeastSupertype(arrayOfString, ARRAY_TYPE)); assertTypeEquals( ARRAY_TYPE, JSType.getLeastSupertype(ARRAY_TYPE, arrayOfString)); assertEquals( "(Array|Object.<string,?>)", JSType.getLeastSupertype(objectOfString, ARRAY_TYPE).toString()); assertEquals( "(Array|Object.<string,?>)", JSType.getLeastSupertype(ARRAY_TYPE, objectOfString).toString()); assertEquals( "Array", JSType.getLeastSupertype(arrayOfString, arrayOfNumber).toString()); assertEquals( "Array", JSType.getLeastSupertype(arrayOfNumber, arrayOfString).toString()); assertTypeEquals( arrayOfString, JSType.getLeastSupertype(arrayOfString, arrayOfString)); assertEquals( "(Array.<string>|Object.<string,?>)", JSType.getLeastSupertype(objectOfString, arrayOfString).toString()); assertEquals( "(Array.<string>|Object.<string,?>)", JSType.getLeastSupertype(arrayOfString, objectOfString).toString()); assertTypeEquals( objectOfString, JSType.getGreatestSubtype(OBJECT_TYPE, objectOfString)); assertTypeEquals( objectOfString, JSType.getGreatestSubtype(objectOfString, OBJECT_TYPE)); assertTypeEquals( ARRAY_TYPE, JSType.getGreatestSubtype(objectOfString, ARRAY_TYPE)); assertTypeEquals( JSType.getGreatestSubtype(objectOfString, arrayOfString), NO_OBJECT_TYPE); assertTypeEquals( JSType.getGreatestSubtype(OBJECT_TYPE, arrayOfString), arrayOfString); } /** * Tests that the given chain of types has a total ordering defined * by the subtype relationship, with types at the top of the lattice * listed first. * * Also verifies that the infimum of any two types on the chain * is the lower type, and the supremum of any two types on the chain * is the higher type. */ public void verifySubtypeChain(List<JSType> typeChain) throws Exception { verifySubtypeChain(typeChain, true); } public void verifySubtypeChain(List<JSType> typeChain, boolean checkSubtyping) throws Exception { // Ugh. This wouldn't require so much copy-and-paste if we had a functional // programming language. for (int i = 0; i < typeChain.size(); i++) { for (int j = 0; j < typeChain.size(); j++) { JSType typeI = typeChain.get(i); JSType typeJ = typeChain.get(j); JSType namedTypeI = getNamedWrapper("TypeI", typeI); JSType namedTypeJ = getNamedWrapper("TypeJ", typeJ); JSType proxyTypeI = new ProxyObjectType(registry, typeI); JSType proxyTypeJ = new ProxyObjectType(registry, typeJ); if (i == j) { assertTrue(typeI + " should equal itself", typeI.isEquivalentTo(typeI)); assertTrue("Named " + typeI + " should equal itself", namedTypeI.isEquivalentTo(namedTypeI)); assertTrue("Proxy " + typeI + " should equal itself", proxyTypeI.isEquivalentTo(proxyTypeI)); } else { assertFalse(typeI + " should not equal " + typeJ, typeI.isEquivalentTo(typeJ)); assertFalse("Named " + typeI + " should not equal " + typeJ, namedTypeI.isEquivalentTo(namedTypeJ)); assertFalse("Proxy " + typeI + " should not equal " + typeJ, proxyTypeI.isEquivalentTo(proxyTypeJ)); } assertTrue(typeJ + " should be castable to " + typeI, typeJ.canCastTo(typeI)); assertTrue(typeJ + " should be castable to Named " + namedTypeI, typeJ.canCastTo(namedTypeI)); assertTrue(typeJ + " should be castable to Proxy " + proxyTypeI, typeJ.canCastTo(proxyTypeI)); assertTrue( "Named " + typeJ + " should be castable to " + typeI, namedTypeJ.canCastTo(typeI)); assertTrue( "Named " + typeJ + " should be castable to Named " + typeI, namedTypeJ.canCastTo(namedTypeI)); assertTrue( "Named " + typeJ + " should be castable to Proxy " + typeI, namedTypeJ.canCastTo(proxyTypeI)); assertTrue( "Proxy " + typeJ + " should be castable to " + typeI, proxyTypeJ.canCastTo(typeI)); assertTrue( "Proxy " + typeJ + " should be castable to Named " + typeI, proxyTypeJ.canCastTo(namedTypeI)); assertTrue( "Proxy " + typeJ + " should be castable to Proxy " + typeI, proxyTypeJ.canCastTo(proxyTypeI)); if (checkSubtyping) { if (i <= j) { assertTrue(typeJ + " should be a subtype of " + typeI, typeJ.isSubtype(typeI)); assertTrue( "Named " + typeJ + " should be a subtype of Named " + typeI, namedTypeJ.isSubtype(namedTypeI)); assertTrue( "Proxy " + typeJ + " should be a subtype of Proxy " + typeI, proxyTypeJ.isSubtype(proxyTypeI)); } else { assertFalse(typeJ + " should not be a subtype of " + typeI, typeJ.isSubtype(typeI)); assertFalse( "Named " + typeJ + " should not be a subtype of Named " + typeI, namedTypeJ.isSubtype(namedTypeI)); assertFalse( "Named " + typeJ + " should not be a subtype of Named " + typeI, proxyTypeJ.isSubtype(proxyTypeI)); } JSType expectedSupremum = i < j ? typeI : typeJ; JSType expectedInfimum = i > j ? typeI : typeJ; assertTypeEquals( expectedSupremum + " should be the least supertype of " + typeI + " and " + typeJ, expectedSupremum, typeI.getLeastSupertype(typeJ)); // TODO(nicksantos): Should these tests pass? //assertTypeEquals( // expectedSupremum + " should be the least supertype of Named " + // typeI + " and Named " + typeJ, // expectedSupremum, namedTypeI.getLeastSupertype(namedTypeJ)); //assertTypeEquals( // expectedSupremum + " should be the least supertype of Proxy " + // typeI + " and Proxy " + typeJ, // expectedSupremum, proxyTypeI.getLeastSupertype(proxyTypeJ)); assertTypeEquals( expectedInfimum + " should be the greatest subtype of " + typeI + " and " + typeJ, expectedInfimum, typeI.getGreatestSubtype(typeJ)); // TODO(nicksantos): Should these tests pass? //assertTypeEquals( // expectedInfimum + " should be the greatest subtype of Named " + // typeI + " and Named " + typeJ, // expectedInfimum, namedTypeI.getGreatestSubtype(namedTypeJ)); //assertTypeEquals( // expectedInfimum + " should be the greatest subtype of Proxy " + // typeI + " and Proxy " + typeJ, // expectedInfimum, proxyTypeI.getGreatestSubtype(proxyTypeJ)); } } } } JSType getNamedWrapper(String name, JSType jstype) { // Normally, there is no way to create a Named NoType alias so // avoid confusing things by doing it here.. if (!jstype.isNoType()) { NamedType namedWrapper = new NamedType( registry, name, "[testcode]", -1, -1); namedWrapper.setReferencedType(jstype); return namedWrapper; } else { return jstype; } } /** * Tests the behavior of * {@link JSType#getRestrictedTypeGivenToBooleanOutcome(boolean)}. */ @SuppressWarnings("checked") public void testRestrictedTypeGivenToBoolean() { // simple cases assertTypeEquals(BOOLEAN_TYPE, BOOLEAN_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(BOOLEAN_TYPE, BOOLEAN_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(NO_TYPE, NULL_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(NULL_TYPE, NULL_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(NUMBER_TYPE, NUMBER_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(NUMBER_TYPE, NUMBER_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(STRING_TYPE, STRING_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(STRING_TYPE, STRING_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(STRING_OBJECT_TYPE, STRING_OBJECT_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(NO_TYPE, STRING_OBJECT_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(NO_TYPE, VOID_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(VOID_TYPE, VOID_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(NO_OBJECT_TYPE, NO_OBJECT_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(NO_TYPE, NO_OBJECT_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(NO_TYPE, NO_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(NO_TYPE, NO_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(CHECKED_UNKNOWN_TYPE, UNKNOWN_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); // unions UnionType nullableStringValue = (UnionType) createNullableType(STRING_TYPE); assertTypeEquals(STRING_TYPE, nullableStringValue.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(nullableStringValue, nullableStringValue.getRestrictedTypeGivenToBooleanOutcome(false)); UnionType nullableStringObject = (UnionType) createNullableType(STRING_OBJECT_TYPE); assertTypeEquals(STRING_OBJECT_TYPE, nullableStringObject.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(NULL_TYPE, nullableStringObject.getRestrictedTypeGivenToBooleanOutcome(false)); } public void testRegisterProperty() { int i = 0; List<JSType> allObjects = Lists.newArrayList(); for (JSType type : types) { String propName = "ALF" + i++; if (type instanceof ObjectType) { ObjectType objType = (ObjectType) type; objType.defineDeclaredProperty(propName, UNKNOWN_TYPE, null); objType.defineDeclaredProperty("allHaz", UNKNOWN_TYPE, null); assertTypeEquals(type, registry.getGreatestSubtypeWithProperty(type, propName)); List<JSType> typesWithProp = Lists.newArrayList(registry.getTypesWithProperty(propName)); String message = type.toString(); assertEquals(message, 1, typesWithProp.size()); assertTypeEquals(type, typesWithProp.get(0)); assertTypeEquals(NO_TYPE, registry.getGreatestSubtypeWithProperty(type, "GRRR")); allObjects.add(type); } } assertTypeListEquals(registry.getTypesWithProperty("GRRR"), Lists.newArrayList(NO_TYPE)); assertTypeListEquals(allObjects, registry.getTypesWithProperty("allHaz")); } public void testRegisterPropertyMemoization() { ObjectType derived1 = registry.createObjectType("d1", null, namedGoogBar); ObjectType derived2 = registry.createObjectType("d2", null, namedGoogBar); derived1.defineDeclaredProperty("propz", UNKNOWN_TYPE, null); assertTypeEquals(derived1, registry.getGreatestSubtypeWithProperty(derived1, "propz")); assertTypeEquals(NO_OBJECT_TYPE, registry.getGreatestSubtypeWithProperty(derived2, "propz")); derived2.defineDeclaredProperty("propz", UNKNOWN_TYPE, null); assertTypeEquals(derived1, registry.getGreatestSubtypeWithProperty(derived1, "propz")); assertTypeEquals(derived2, registry.getGreatestSubtypeWithProperty(derived2, "propz")); } /** * Tests * {@link JSTypeRegistry#getGreatestSubtypeWithProperty(JSType, String)}. */ public void testGreatestSubtypeWithProperty() { ObjectType foo = registry.createObjectType("foo", null, OBJECT_TYPE); ObjectType bar = registry.createObjectType("bar", null, namedGoogBar); foo.defineDeclaredProperty("propz", UNKNOWN_TYPE, null); bar.defineDeclaredProperty("propz", UNKNOWN_TYPE, null); assertTypeEquals(bar, registry.getGreatestSubtypeWithProperty(namedGoogBar, "propz")); } public void testGoodSetPrototypeBasedOn() { FunctionType fun = registry.createConstructorType( "fun", null, null, null, null); fun.setPrototypeBasedOn(unresolvedNamedType); assertTrue(fun.getInstanceType().isUnknownType()); } public void testLateSetPrototypeBasedOn() { FunctionType fun = registry.createConstructorType( "fun", null, null, null, null); assertFalse(fun.getInstanceType().isUnknownType()); fun.setPrototypeBasedOn(unresolvedNamedType); assertTrue(fun.getInstanceType().isUnknownType()); } public void testGetTypeUnderEquality1() { for (JSType type : types) { testGetTypeUnderEquality(type, type, type, type); } } public void testGetTypesUnderEquality2() { // objects can be equal to numbers testGetTypeUnderEquality( NUMBER_TYPE, OBJECT_TYPE, NUMBER_TYPE, OBJECT_TYPE); } public void testGetTypesUnderEquality3() { // null == undefined testGetTypeUnderEquality( NULL_TYPE, VOID_TYPE, NULL_TYPE, VOID_TYPE); } @SuppressWarnings("checked") public void testGetTypesUnderEquality4() { // (number,string) and number/string UnionType stringNumber = (UnionType) createUnionType(NUMBER_TYPE, STRING_TYPE); testGetTypeUnderEquality( stringNumber, STRING_TYPE, stringNumber, STRING_TYPE); testGetTypeUnderEquality( stringNumber, NUMBER_TYPE, stringNumber, NUMBER_TYPE); } public void testGetTypesUnderEquality5() { // (number,null) and undefined JSType nullUndefined = createUnionType(VOID_TYPE, NULL_TYPE); testGetTypeUnderEquality( nullUndefined, NULL_TYPE, nullUndefined, NULL_TYPE); testGetTypeUnderEquality( nullUndefined, VOID_TYPE, nullUndefined, VOID_TYPE); } public void testGetTypesUnderEquality6() { // (number,undefined,null) == null JSType optNullNumber = createUnionType(VOID_TYPE, NULL_TYPE, NUMBER_TYPE); testGetTypeUnderEquality( optNullNumber, NULL_TYPE, createUnionType(NULL_TYPE, VOID_TYPE), NULL_TYPE); } private void testGetTypeUnderEquality( JSType t1, JSType t2, JSType t1Eq, JSType t2Eq) { // creating the pairs TypePair p12 = t1.getTypesUnderEquality(t2); TypePair p21 = t2.getTypesUnderEquality(t1); // t1Eq assertTypeEquals(t1Eq, p12.typeA); assertTypeEquals(t1Eq, p21.typeB); // t2Eq assertTypeEquals(t2Eq, p12.typeB); assertTypeEquals(t2Eq, p21.typeA); } @SuppressWarnings("checked") public void testGetTypesUnderInequality1() { // objects can be not equal to numbers UnionType numberObject = (UnionType) createUnionType(NUMBER_TYPE, OBJECT_TYPE); testGetTypesUnderInequality( numberObject, NUMBER_TYPE, numberObject, NUMBER_TYPE); testGetTypesUnderInequality( numberObject, OBJECT_TYPE, numberObject, OBJECT_TYPE); } @SuppressWarnings("checked") public void testGetTypesUnderInequality2() { // null == undefined UnionType nullUndefined = (UnionType) createUnionType(VOID_TYPE, NULL_TYPE); testGetTypesUnderInequality( nullUndefined, NULL_TYPE, NO_TYPE, NO_TYPE); testGetTypesUnderInequality( nullUndefined, VOID_TYPE, NO_TYPE, NO_TYPE); } @SuppressWarnings("checked") public void testGetTypesUnderInequality3() { // (number,string) UnionType stringNumber = (UnionType) createUnionType(NUMBER_TYPE, STRING_TYPE); testGetTypesUnderInequality( stringNumber, NUMBER_TYPE, stringNumber, NUMBER_TYPE); testGetTypesUnderInequality( stringNumber, STRING_TYPE, stringNumber, STRING_TYPE); } @SuppressWarnings("checked") public void testGetTypesUnderInequality4() throws Exception { // (number,undefined,null) and null UnionType nullableOptionalNumber = (UnionType) createUnionType(NULL_TYPE, VOID_TYPE, NUMBER_TYPE); testGetTypesUnderInequality( nullableOptionalNumber, NULL_TYPE, NUMBER_TYPE, NULL_TYPE); } private void testGetTypesUnderInequality( JSType t1, JSType t2, JSType t1Eq, JSType t2Eq) { // creating the pairs TypePair p12 = t1.getTypesUnderInequality(t2); TypePair p21 = t2.getTypesUnderInequality(t1); // t1Eq assertTypeEquals(t1Eq, p12.typeA); assertTypeEquals(t1Eq, p21.typeB); // t2Eq assertTypeEquals(t2Eq, p12.typeB); assertTypeEquals(t2Eq, p21.typeA); } /** * Tests the factory method * {@link JSTypeRegistry#createRecordType}. */ public void testCreateRecordType() throws Exception { Map<String, RecordProperty> properties = new HashMap<String, RecordProperty>(); properties.put("hello", new RecordProperty(NUMBER_TYPE, null)); JSType recordType = registry.createRecordType(properties); assertEquals("{hello: number}", recordType.toString()); } /** * Tests the factory method {@link JSTypeRegistry#createOptionalType(JSType)}. */ public void testCreateOptionalType() throws Exception { // number UnionType optNumber = (UnionType) registry.createOptionalType(NUMBER_TYPE); assertUnionContains(optNumber, NUMBER_TYPE); assertUnionContains(optNumber, VOID_TYPE); // union UnionType optUnion = (UnionType) registry.createOptionalType( createUnionType(STRING_OBJECT_TYPE, DATE_TYPE)); assertUnionContains(optUnion, DATE_TYPE); assertUnionContains(optUnion, STRING_OBJECT_TYPE); assertUnionContains(optUnion, VOID_TYPE); } public void assertUnionContains(UnionType union, JSType type) { assertTrue(union + " should contain " + type, union.contains(type)); } /** * Tests the factory method * {@link JSTypeRegistry#createAnonymousObjectType}}. */ public void testCreateAnonymousObjectType() throws Exception { // anonymous ObjectType anonymous = registry.createAnonymousObjectType(null); assertTypeEquals(OBJECT_TYPE, anonymous.getImplicitPrototype()); assertNull(anonymous.getReferenceName()); assertEquals("{}", anonymous.toString()); } /** * Tests the factory method * {@link JSTypeRegistry#createAnonymousObjectType}} and adds * some properties to it. */ public void testCreateAnonymousObjectType2() throws Exception { // anonymous ObjectType anonymous = registry.createAnonymousObjectType(null); anonymous.defineDeclaredProperty( "a", NUMBER_TYPE, null); anonymous.defineDeclaredProperty( "b", NUMBER_TYPE, null); anonymous.defineDeclaredProperty( "c", NUMBER_TYPE, null); anonymous.defineDeclaredProperty( "d", NUMBER_TYPE, null); anonymous.defineDeclaredProperty( "e", NUMBER_TYPE, null); anonymous.defineDeclaredProperty( "f", NUMBER_TYPE, null); assertEquals("{a: number, b: number, c: number, d: number, ...}", anonymous.toString()); } /** * Tests the factory methods * {@link JSTypeRegistry#createObjectType(ObjectType)}} and * {@link JSTypeRegistry#createObjectType(String, Node, ObjectType)}}. */ public void testCreateObjectType() throws Exception { // simple ObjectType subDate = registry.createObjectType(DATE_TYPE.getImplicitPrototype()); assertTypeEquals(DATE_TYPE.getImplicitPrototype(), subDate.getImplicitPrototype()); assertNull(subDate.getReferenceName()); assertEquals("{...}", subDate.toString()); // name, node, prototype ObjectType subError = registry.createObjectType("Foo", null, ERROR_TYPE.getImplicitPrototype()); assertTypeEquals(ERROR_TYPE.getImplicitPrototype(), subError.getImplicitPrototype()); assertEquals("Foo", subError.getReferenceName()); } /** * Tests {@code (U2U_CONSTRUCTOR,undefined) <: (U2U_CONSTRUCTOR,undefined)}. */ @SuppressWarnings("checked") public void testBug903110() throws Exception { UnionType union = (UnionType) createUnionType(U2U_CONSTRUCTOR_TYPE, VOID_TYPE); assertTrue(VOID_TYPE.isSubtype(union)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(union)); assertTrue(union.isSubtype(union)); } /** * Tests {@code U2U_FUNCTION_TYPE <: U2U_CONSTRUCTOR} and * {@code U2U_FUNCTION_TYPE <: (U2U_CONSTRUCTOR,undefined)}. */ public void testBug904123() throws Exception { assertTrue(U2U_FUNCTION_TYPE.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_FUNCTION_TYPE. isSubtype(createOptionalType(U2U_CONSTRUCTOR_TYPE))); } /** * Assert that a type can assign to itself. */ private void assertTypeCanAssignToItself(JSType type) { assertTrue(type.isSubtype(type)); } /** * Tests that hasOwnProperty returns true when a property is defined directly * on a class and false if the property is defined on the supertype or not at * all. */ public void testHasOwnProperty() throws Exception { ObjectType sup = registry.createObjectType(registry.createAnonymousObjectType(null)); ObjectType sub = registry.createObjectType(sup); sup.defineProperty("base", null, false, null); sub.defineProperty("sub", null, false, null); assertTrue(sup.hasProperty("base")); assertFalse(sup.hasProperty("sub")); assertTrue(sup.hasOwnProperty("base")); assertFalse(sup.hasOwnProperty("sub")); assertFalse(sup.hasOwnProperty("none")); assertTrue(sub.hasProperty("base")); assertTrue(sub.hasProperty("sub")); assertFalse(sub.hasOwnProperty("base")); assertTrue(sub.hasOwnProperty("sub")); assertFalse(sub.hasOwnProperty("none")); } public void testNamedTypeHasOwnProperty() throws Exception { namedGoogBar.getImplicitPrototype().defineProperty("base", null, false, null); namedGoogBar.defineProperty("sub", null, false, null); assertFalse(namedGoogBar.hasOwnProperty("base")); assertTrue(namedGoogBar.hasProperty("base")); assertTrue(namedGoogBar.hasOwnProperty("sub")); assertTrue(namedGoogBar.hasProperty("sub")); } public void testInterfaceHasOwnProperty() throws Exception { interfaceInstType.defineProperty("base", null, false, null); subInterfaceInstType.defineProperty("sub", null, false, null); assertTrue(interfaceInstType.hasProperty("base")); assertFalse(interfaceInstType.hasProperty("sub")); assertTrue(interfaceInstType.hasOwnProperty("base")); assertFalse(interfaceInstType.hasOwnProperty("sub")); assertFalse(interfaceInstType.hasOwnProperty("none")); assertTrue(subInterfaceInstType.hasProperty("base")); assertTrue(subInterfaceInstType.hasProperty("sub")); assertFalse(subInterfaceInstType.hasOwnProperty("base")); assertTrue(subInterfaceInstType.hasOwnProperty("sub")); assertFalse(subInterfaceInstType.hasOwnProperty("none")); } public void testGetPropertyNames() throws Exception { ObjectType sup = registry.createObjectType(registry.createAnonymousObjectType(null)); ObjectType sub = registry.createObjectType(sup); sup.defineProperty("base", null, false, null); sub.defineProperty("sub", null, false, null); assertEquals(Sets.newHashSet("isPrototypeOf", "toLocaleString", "propertyIsEnumerable", "toString", "valueOf", "hasOwnProperty", "constructor", "base", "sub"), sub.getPropertyNames()); assertEquals(Sets.newHashSet("isPrototypeOf", "toLocaleString", "propertyIsEnumerable", "toString", "valueOf", "hasOwnProperty", "constructor", "base"), sup.getPropertyNames()); assertEquals(Sets.newHashSet(), NO_OBJECT_TYPE.getPropertyNames()); } public void testGetAndSetJSDocInfoWithNamedType() throws Exception { JSDocInfo info = new JSDocInfo(); info.setDeprecated(true); assertNull(namedGoogBar.getOwnPropertyJSDocInfo("X")); namedGoogBar.setPropertyJSDocInfo("X", info); assertTrue(namedGoogBar.getOwnPropertyJSDocInfo("X").isDeprecated()); assertPropertyTypeInferred(namedGoogBar, "X"); assertTypeEquals(UNKNOWN_TYPE, namedGoogBar.getPropertyType("X")); } public void testGetAndSetJSDocInfoWithObjectTypes() throws Exception { ObjectType sup = registry.createObjectType(registry.createAnonymousObjectType(null)); ObjectType sub = registry.createObjectType(sup); JSDocInfo deprecated = new JSDocInfo(); deprecated.setDeprecated(true); JSDocInfo privateInfo = new JSDocInfo(); privateInfo.setVisibility(Visibility.PRIVATE); sup.defineProperty("X", NUMBER_TYPE, true, null); sup.setPropertyJSDocInfo("X", privateInfo); sub.defineProperty("X", NUMBER_TYPE, true, null); sub.setPropertyJSDocInfo("X", deprecated); assertFalse(sup.getOwnPropertyJSDocInfo("X").isDeprecated()); assertEquals(Visibility.PRIVATE, sup.getOwnPropertyJSDocInfo("X").getVisibility()); assertTypeEquals(NUMBER_TYPE, sup.getPropertyType("X")); assertTrue(sub.getOwnPropertyJSDocInfo("X").isDeprecated()); assertNull(sub.getOwnPropertyJSDocInfo("X").getVisibility()); assertTypeEquals(NUMBER_TYPE, sub.getPropertyType("X")); } public void testGetAndSetJSDocInfoWithNoType() throws Exception { JSDocInfo deprecated = new JSDocInfo(); deprecated.setDeprecated(true); NO_TYPE.setPropertyJSDocInfo("X", deprecated); assertNull(NO_TYPE.getOwnPropertyJSDocInfo("X")); } public void testObjectGetSubTypes() throws Exception { assertTrue( containsType( OBJECT_FUNCTION_TYPE.getSubTypes(), googBar)); assertTrue( containsType( googBar.getSubTypes(), googSubBar)); assertFalse( containsType( googBar.getSubTypes(), googSubSubBar)); assertFalse( containsType( googSubBar.getSubTypes(), googSubBar)); assertTrue( containsType( googSubBar.getSubTypes(), googSubSubBar)); } public void testImplementingType() throws Exception { assertTrue( containsType( registry.getDirectImplementors( interfaceType.getInstanceType()), googBar)); } public void testIsTemplatedType() throws Exception { assertTrue( new TemplateType(registry, "T") .hasAnyTemplateTypes()); assertFalse(ARRAY_TYPE.hasAnyTemplateTypes()); assertTrue( createTemplatizedType(ARRAY_TYPE, new TemplateType(registry, "T")) .hasAnyTemplateTypes()); assertFalse( createTemplatizedType(ARRAY_TYPE, STRING_TYPE).hasAnyTemplateTypes()); assertTrue( new FunctionBuilder(registry) .withReturnType(new TemplateType(registry, "T")) .build() .hasAnyTemplateTypes()); assertTrue( new FunctionBuilder(registry) .withTypeOfThis(new TemplateType(registry, "T")) .build() .hasAnyTemplateTypes()); assertFalse( new FunctionBuilder(registry) .withReturnType(STRING_TYPE) .build() .hasAnyTemplateTypes()); assertTrue( registry.createUnionType( NULL_TYPE, new TemplateType(registry, "T"), STRING_TYPE) .hasAnyTemplateTypes()); assertFalse( registry.createUnionType( NULL_TYPE, ARRAY_TYPE, STRING_TYPE) .hasAnyTemplateTypes()); } public void testTemplatizedType() throws Exception { FunctionType templatizedCtor = registry.createConstructorType( "TestingType", null, null, UNKNOWN_TYPE, ImmutableList.of( registry.createTemplateType("A"), registry.createTemplateType("B"))); JSType templatizedInstance = registry.createTemplatizedType( templatizedCtor.getInstanceType(), ImmutableList.of(NUMBER_TYPE, STRING_TYPE)); TemplateTypeMap ctrTypeMap = templatizedCtor.getTemplateTypeMap(); TemplateType keyA = ctrTypeMap.getTemplateTypeKeyByName("A"); assertNotNull(keyA); TemplateType keyB = ctrTypeMap.getTemplateTypeKeyByName("B"); assertNotNull(keyB); TemplateType keyC = ctrTypeMap.getTemplateTypeKeyByName("C"); assertNull(keyC); TemplateType unknownKey = registry.createTemplateType("C"); TemplateTypeMap templateTypeMap = templatizedInstance.getTemplateTypeMap(); assertTrue(templateTypeMap.hasTemplateKey(keyA)); assertTrue(templateTypeMap.hasTemplateKey(keyB)); assertFalse(templateTypeMap.hasTemplateKey(unknownKey)); assertEquals(NUMBER_TYPE, templateTypeMap.getTemplateType(keyA)); assertEquals(STRING_TYPE, templateTypeMap.getTemplateType(keyB)); assertEquals(UNKNOWN_TYPE, templateTypeMap.getTemplateType(unknownKey)); assertEquals("TestingType.<number,string>", templatizedInstance.toString()); } public void testPartiallyTemplatizedType() throws Exception { FunctionType templatizedCtor = registry.createConstructorType( "TestingType", null, null, UNKNOWN_TYPE, ImmutableList.of( registry.createTemplateType("A"), registry.createTemplateType("B"))); JSType templatizedInstance = registry.createTemplatizedType( templatizedCtor.getInstanceType(), ImmutableList.of(NUMBER_TYPE)); TemplateTypeMap ctrTypeMap = templatizedCtor.getTemplateTypeMap(); TemplateType keyA = ctrTypeMap.getTemplateTypeKeyByName("A"); assertNotNull(keyA); TemplateType keyB = ctrTypeMap.getTemplateTypeKeyByName("B"); assertNotNull(keyB); TemplateType keyC = ctrTypeMap.getTemplateTypeKeyByName("C"); assertNull(keyC); TemplateType unknownKey = registry.createTemplateType("C"); TemplateTypeMap templateTypeMap = templatizedInstance.getTemplateTypeMap(); assertTrue(templateTypeMap.hasTemplateKey(keyA)); assertTrue(templateTypeMap.hasTemplateKey(keyB)); assertFalse(templateTypeMap.hasTemplateKey(unknownKey)); assertEquals(NUMBER_TYPE, templateTypeMap.getTemplateType(keyA)); assertEquals(UNKNOWN_TYPE, templateTypeMap.getTemplateType(keyB)); assertEquals(UNKNOWN_TYPE, templateTypeMap.getTemplateType(unknownKey)); assertEquals("TestingType.<number,?>", templatizedInstance.toString()); } public void testCanCastTo() { assertTrue(ALL_TYPE.canCastTo(NULL_TYPE)); assertTrue(ALL_TYPE.canCastTo(VOID_TYPE)); assertTrue(ALL_TYPE.canCastTo(STRING_TYPE)); assertTrue(ALL_TYPE.canCastTo(NUMBER_TYPE)); assertTrue(ALL_TYPE.canCastTo(BOOLEAN_TYPE)); assertTrue(ALL_TYPE.canCastTo(OBJECT_TYPE)); assertFalse(NUMBER_TYPE.canCastTo(NULL_TYPE)); assertFalse(NUMBER_TYPE.canCastTo(VOID_TYPE)); assertFalse(NUMBER_TYPE.canCastTo(STRING_TYPE)); assertTrue(NUMBER_TYPE.canCastTo(NUMBER_TYPE)); assertFalse(NUMBER_TYPE.canCastTo(BOOLEAN_TYPE)); assertFalse(NUMBER_TYPE.canCastTo(OBJECT_TYPE)); assertFalse(STRING_TYPE.canCastTo(NULL_TYPE)); assertFalse(STRING_TYPE.canCastTo(VOID_TYPE)); assertTrue(STRING_TYPE.canCastTo(STRING_TYPE)); assertFalse(STRING_TYPE.canCastTo(NUMBER_TYPE)); assertFalse(STRING_TYPE.canCastTo(BOOLEAN_TYPE)); assertFalse(STRING_TYPE.canCastTo(OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.canCastTo(NULL_TYPE)); assertFalse(BOOLEAN_TYPE.canCastTo(VOID_TYPE)); assertFalse(BOOLEAN_TYPE.canCastTo(STRING_TYPE)); assertFalse(BOOLEAN_TYPE.canCastTo(NUMBER_TYPE)); assertTrue(BOOLEAN_TYPE.canCastTo(BOOLEAN_TYPE)); assertFalse(BOOLEAN_TYPE.canCastTo(OBJECT_TYPE)); assertFalse(OBJECT_TYPE.canCastTo(NULL_TYPE)); assertFalse(OBJECT_TYPE.canCastTo(VOID_TYPE)); assertFalse(OBJECT_TYPE.canCastTo(STRING_TYPE)); assertFalse(OBJECT_TYPE.canCastTo(NUMBER_TYPE)); assertFalse(OBJECT_TYPE.canCastTo(BOOLEAN_TYPE)); assertTrue(OBJECT_TYPE.canCastTo(OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.canCastTo(OBJECT_NUMBER_STRING)); assertFalse(OBJECT_NUMBER_STRING.canCastTo(BOOLEAN_TYPE)); assertFalse(ARRAY_TYPE.canCastTo(U2U_FUNCTION_TYPE)); assertFalse(U2U_FUNCTION_TYPE.canCastTo(ARRAY_TYPE)); assertFalse(NULL_VOID.canCastTo(ARRAY_TYPE)); assertTrue(NULL_VOID.canCastTo(createUnionType(ARRAY_TYPE, NULL_TYPE))); // We currently allow any function to be cast to any other function type assertTrue(ARRAY_FUNCTION_TYPE.canCastTo(BOOLEAN_OBJECT_FUNCTION_TYPE)); } private static boolean containsType( Iterable<? extends JSType> types, JSType type) { for (JSType alt : types) { if (alt.isEquivalentTo(type)) { return true; } } return false; } private static boolean assertTypeListEquals( Iterable<? extends JSType> typeListA, Iterable<? extends JSType> typeListB) { for (JSType alt : typeListA) { assertTrue( "List : " + typeListA + "\n" + "does not contain: " + alt, containsType(typeListA, alt)); } for (JSType alt : typeListB) { assertTrue( "List : " + typeListB + "\n" + "does not contain: " + alt, containsType(typeListB, alt)); } return false; } private ArrowType createArrowType(Node params) { return registry.createArrowType(params); } }
[ { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "checkEquivalenceHelper", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/JSType;Lcom/google/javascript/rhino/jstype/EquivalenceMethod;)Z", "line_numbers": [ "572", "573", "576", "577", "578", "579", "582", "583", "586", "587", "592", "596", "597", "601", "602", "606", "607", "611", "613", "616", "618", "622", "625", "629", "630", "635", "636", "645" ], "method_line_rate": 0.5714285714285714 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "equals", "be_test_function_signature": "(Ljava/lang/Object;)Z", "line_numbers": [ "667" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "extendTemplateTypeMap", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/TemplateTypeMap;)V", "line_numbers": [ "464", "465" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "getConcreteNominalTypeName", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/ObjectType;)Ljava/lang/String;", "line_numbers": [ "650", "651", "653", "654", "657" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "getNativeType", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/JSTypeNative;)Lcom/google/javascript/rhino/jstype/JSType;", "line_numbers": [ "122" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "getTemplateTypeMap", "be_test_function_signature": "()Lcom/google/javascript/rhino/jstype/TemplateTypeMap;", "line_numbers": [ "456" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "hasAnyTemplateTypes", "be_test_function_signature": "()Z", "line_numbers": [ "437", "438", "439", "440", "441", "444" ], "method_line_rate": 0.8333333333333334 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "hasAnyTemplateTypesInternal", "be_test_function_signature": "()Z", "line_numbers": [ "449" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "hashCode", "be_test_function_signature": "()I", "line_numbers": [ "673" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isAllType", "be_test_function_signature": "()Z", "line_numbers": [ "253" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isEmptyType", "be_test_function_signature": "()Z", "line_numbers": [ "176" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isEquivalentTo", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/JSType;)Z", "line_numbers": [ "543" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isExemptFromTemplateTypeInvariance", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/JSType;)Z", "line_numbers": [ "1323", "1324" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isFunctionType", "be_test_function_signature": "()Z", "line_numbers": [ "334" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isNoObjectType", "be_test_function_signature": "()Z", "line_numbers": [ "172" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isNoResolvedType", "be_test_function_signature": "()Z", "line_numbers": [ "168" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isNoType", "be_test_function_signature": "()Z", "line_numbers": [ "164" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isNominalType", "be_test_function_signature": "()Z", "line_numbers": [ "488" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isRecordType", "be_test_function_signature": "()Z", "line_numbers": [ "387" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isResolved", "be_test_function_signature": "()Z", "line_numbers": [ "1383" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isSubtype", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/JSType;)Z", "line_numbers": [ "1249" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isSubtypeHelper", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/JSType;Lcom/google/javascript/rhino/jstype/JSType;)Z", "line_numbers": [ "1258", "1259", "1262", "1263", "1266", "1267", "1270", "1271", "1272", "1273", "1274", "1276", "1277", "1282", "1283", "1284", "1285", "1289", "1290", "1291", "1293", "1295", "1296", "1299", "1300", "1305", "1306", "1311", "1312", "1315" ], "method_line_rate": 0.6 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isTemplateType", "be_test_function_signature": "()Z", "line_numbers": [ "418" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isTemplatizedType", "be_test_function_signature": "()Z", "line_numbers": [ "399" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isUnionType", "be_test_function_signature": "()Z", "line_numbers": [ "265" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isUnknownType", "be_test_function_signature": "()Z", "line_numbers": [ "257" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "resolve", "be_test_function_signature": "(Lcom/google/javascript/rhino/ErrorReporter;Lcom/google/javascript/rhino/jstype/StaticScope;)Lcom/google/javascript/rhino/jstype/JSType;", "line_numbers": [ "1357", "1360", "1361", "1363", "1365", "1366", "1367", "1368" ], "method_line_rate": 0.875 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "restrictByNotNullOrUndefined", "be_test_function_signature": "()Lcom/google/javascript/rhino/jstype/JSType;", "line_numbers": [ "1219" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "safeResolve", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/JSType;Lcom/google/javascript/rhino/ErrorReporter;Lcom/google/javascript/rhino/jstype/StaticScope;)Lcom/google/javascript/rhino/jstype/JSType;", "line_numbers": [ "1398" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "setResolvedTypeInternal", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/JSType;)V", "line_numbers": [ "1377", "1378", "1379" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "toMaybeFunctionType", "be_test_function_signature": "()Lcom/google/javascript/rhino/jstype/FunctionType;", "line_numbers": [ "350" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "toMaybeRecordType", "be_test_function_signature": "()Lcom/google/javascript/rhino/jstype/RecordType;", "line_numbers": [ "395" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "toMaybeTemplateType", "be_test_function_signature": "()Lcom/google/javascript/rhino/jstype/TemplateType;", "line_numbers": [ "426" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "toMaybeTemplatizedType", "be_test_function_signature": "()Lcom/google/javascript/rhino/jstype/TemplatizedType;", "line_numbers": [ "407" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "toMaybeUnionType", "be_test_function_signature": "()Lcom/google/javascript/rhino/jstype/UnionType;", "line_numbers": [ "324" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "toObjectType", "be_test_function_signature": "()Lcom/google/javascript/rhino/jstype/ObjectType;", "line_numbers": [ "792" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "toString", "be_test_function_signature": "()Ljava/lang/String;", "line_numbers": [ "1427" ], "method_line_rate": 1 } ]
public class TimedSemaphoreTest
@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); }
// // 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 `testAcquireMultipleThreads` for the `TimedSemaphore` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * 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. */
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();
267
testAcquireMultipleThreads
```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 `testAcquireMultipleThreads` for the `TimedSemaphore` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * 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. */
239
// // 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 `testAcquireMultipleThreads` for the `TimedSemaphore` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * 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 {
/** * 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. */
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 `testAcquireMultipleThreads` for the `TimedSemaphore` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * 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 { ```
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();
9f1a6f88a0e2784b1644af328ff5707fce1a0600523ba04f890589d5833d4b46
[ "org.apache.commons.lang3.concurrent.TimedSemaphoreTest::testAcquireMultipleThreads" ]
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 testAcquireMultipleThreads() 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": "getAcquireCount", "be_test_function_signature": "()I", "line_numbers": [ "333" ], "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": "getLastAcquiresPerPeriod", "be_test_function_signature": "()I", "line_numbers": [ "323" ], "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": "startTimer", "be_test_function_signature": "()Ljava/util/concurrent/ScheduledFuture;", "line_numbers": [ "402" ], "method_line_rate": 1 } ]
public class ExtendedMessageFormatTest
@Test public void testBuiltInChoiceFormat() { final Object[] values = new Number[] {Integer.valueOf(1), Double.valueOf("2.2"), Double.valueOf("1234.5")}; String choicePattern = null; final Locale[] availableLocales = ChoiceFormat.getAvailableLocales(); choicePattern = "{0,choice,1#One|2#Two|3#Many {0,number}}"; for (final Object value : values) { checkBuiltInFormat(value + ": " + choicePattern, new Object[] {value}, availableLocales); } choicePattern = "{0,choice,1#''One''|2#\"Two\"|3#''{Many}'' {0,number}}"; for (final Object value : values) { checkBuiltInFormat(value + ": " + choicePattern, new Object[] {value}, availableLocales); } }
// // Abstract Java Tested Class // package org.apache.commons.lang3.text; // // import java.text.Format; // import java.text.MessageFormat; // import java.text.ParsePosition; // import java.util.ArrayList; // import java.util.Collection; // import java.util.Iterator; // import java.util.Locale; // import java.util.Map; // import org.apache.commons.lang3.ObjectUtils; // import org.apache.commons.lang3.Validate; // // // // public class ExtendedMessageFormat extends MessageFormat { // private static final long serialVersionUID = -2362048321261811743L; // private static final int HASH_SEED = 31; // private static final String DUMMY_PATTERN = ""; // private static final String ESCAPED_QUOTE = "''"; // private static final char START_FMT = ','; // private static final char END_FE = '}'; // private static final char START_FE = '{'; // private static final char QUOTE = '\''; // private String toPattern; // private final Map<String, ? extends FormatFactory> registry; // // public ExtendedMessageFormat(final String pattern); // public ExtendedMessageFormat(final String pattern, final Locale locale); // public ExtendedMessageFormat(final String pattern, final Map<String, ? extends FormatFactory> registry); // public ExtendedMessageFormat(final String pattern, final Locale locale, final Map<String, ? extends FormatFactory> registry); // @Override // public String toPattern(); // @Override // public final void applyPattern(final String pattern); // @Override // public void setFormat(final int formatElementIndex, final Format newFormat); // @Override // public void setFormatByArgumentIndex(final int argumentIndex, final Format newFormat); // @Override // public void setFormats(final Format[] newFormats); // @Override // public void setFormatsByArgumentIndex(final Format[] newFormats); // @Override // public boolean equals(final Object obj); // @Override // public int hashCode(); // private Format getFormat(final String desc); // private int readArgumentIndex(final String pattern, final ParsePosition pos); // private String parseFormatDescription(final String pattern, final ParsePosition pos); // private String insertFormats(final String pattern, final ArrayList<String> customPatterns); // private void seekNonWs(final String pattern, final ParsePosition pos); // private ParsePosition next(final ParsePosition pos); // private StringBuilder appendQuotedString(final String pattern, final ParsePosition pos, // final StringBuilder appendTo, final boolean escapingOn); // private void getQuotedString(final String pattern, final ParsePosition pos, // final boolean escapingOn); // private boolean containsElements(final Collection<?> coll); // } // // // Abstract Java Test Class // package org.apache.commons.lang3.text; // // import org.junit.Test; // import org.junit.Before; // import static org.junit.Assert.*; // import static org.apache.commons.lang3.JavaVersion.JAVA_1_4; // import java.text.ChoiceFormat; // import java.text.DateFormat; // import java.text.FieldPosition; // import java.text.Format; // import java.text.MessageFormat; // import java.text.NumberFormat; // import java.text.ParsePosition; // import java.util.Arrays; // import java.util.Calendar; // import java.util.Collections; // import java.util.HashMap; // import java.util.HashSet; // import java.util.Locale; // import java.util.Map; // import org.apache.commons.lang3.SystemUtils; // // // // public class ExtendedMessageFormatTest { // private final Map<String, FormatFactory> registry = new HashMap<String, FormatFactory>(); // // @Before // public void setUp() throws Exception; // @Test // public void testExtendedFormats(); // @Test // public void testEscapedQuote_LANG_477(); // @Test // public void testExtendedAndBuiltInFormats(); // @Test // public void testBuiltInChoiceFormat(); // @Test // public void testBuiltInDateTimeFormat(); // @Test // public void testOverriddenBuiltinFormat(); // @Test // public void testBuiltInNumberFormat(); // @Test // public void testEqualsHashcode(); // private void checkBuiltInFormat(final String pattern, final Object[] args, final Locale[] locales); // private void checkBuiltInFormat(final String pattern, final Map<String, ?> registry, final Object[] args, final Locale[] locales); // private void checkBuiltInFormat(final String pattern, final Map<String, ?> registry, final Object[] args, final Locale locale); // private void assertPatternsEqual(final String message, final String expected, final String actual); // private MessageFormat createMessageFormat(final String pattern, final Locale locale); // @Override // public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos); // @Override // public Object parseObject(final String source, final ParsePosition pos); // @Override // public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos); // @Override // public Object parseObject(final String source, final ParsePosition pos); // @Override // public Format getFormat(final String name, final String arguments, final Locale locale); // @Override // public Format getFormat(final String name, final String arguments, final Locale locale); // @Override // public Format getFormat(final String name, final String arguments, final Locale locale); // public OtherExtendedMessageFormat(final String pattern, final Locale locale, // final Map<String, ? extends FormatFactory> registry); // } // You are a professional Java test case writer, please create a test case named `testBuiltInChoiceFormat` for the `ExtendedMessageFormat` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test the built in choice format. */ // } // } // } // // currently sub-formats not supported // } catch (IllegalArgumentException e) { // assertEquals(highExpected, emf.format(highArgs)); // assertEquals(lowExpected, emf.format(lowArgs)); // String highExpected = highArgs[0] + " HIGH " + cf.format(highArgs[2]); // String lowExpected = lowArgs[0] + " low " + nf.format(lowArgs[2]); // try { // assertPatterns(null, pattern, emf.toPattern()); // } // emf = new ExtendedMessageFormat(pattern, testLocales[i], registry); // cf = NumberFormat.getCurrencyInstance(testLocales[i]); // nf = NumberFormat.getNumberInstance(testLocales[i]); // } else { // emf = new ExtendedMessageFormat(pattern, registry); // cf = NumberFormat.getCurrencyInstance(); // nf = NumberFormat.getNumberInstance(); // if (testLocales[i] == null) { // ExtendedMessageFormat emf = null; // NumberFormat cf = null; // NumberFormat nf = null; // for (int i = 0; i < testLocales.length; i++) { // System.arraycopy(availableLocales, 0, testLocales, 1, availableLocales.length); // testLocales[0] = null; // Locale[] testLocales = new Locale[availableLocales.length + 1]; // Locale[] availableLocales = ChoiceFormat.getAvailableLocales(); // Object[] highArgs = new Object[] {Integer.valueOf(2), "High", Double.valueOf("9876.54")}; // Object[] lowArgs = new Object[] {Integer.valueOf(1), "Low", Double.valueOf("1234.56")}; // String pattern = "Choice: {0,choice,1.0#{0} {1,lower} {2,number}|2.0#{0} {1,upper} {2,number,currency}}"; // public void testExtendedAndBuiltInWithChoiceFormat() { // */ // * NOTE: FAILING - currently sub-formats not supported // * // * Test mixed extended and built-in formats with choice format. // /** // } // } // // currently sub-formats not supported // } catch (IllegalArgumentException e) { // assertEquals("TWO", emf.format(new Object[] {Integer.valueOf(2), "two"})); // assertEquals("one", emf.format(new Object[] {Integer.valueOf(1), "ONE"})); // try { // assertPatterns(null, pattern, emf.toPattern()); // ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry); // String pattern = "Choice: {0,choice,1.0#{1,lower}|2.0#{1,upper}}"; // public void testExtendedWithChoiceFormat() { // */
src/test/java/org/apache/commons/lang3/text/ExtendedMessageFormatTest.java
package org.apache.commons.lang3.text; import java.text.Format; import java.text.MessageFormat; import java.text.ParsePosition; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Locale; import java.util.Map; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.Validate;
public ExtendedMessageFormat(final String pattern); public ExtendedMessageFormat(final String pattern, final Locale locale); public ExtendedMessageFormat(final String pattern, final Map<String, ? extends FormatFactory> registry); public ExtendedMessageFormat(final String pattern, final Locale locale, final Map<String, ? extends FormatFactory> registry); @Override public String toPattern(); @Override public final void applyPattern(final String pattern); @Override public void setFormat(final int formatElementIndex, final Format newFormat); @Override public void setFormatByArgumentIndex(final int argumentIndex, final Format newFormat); @Override public void setFormats(final Format[] newFormats); @Override public void setFormatsByArgumentIndex(final Format[] newFormats); @Override public boolean equals(final Object obj); @Override public int hashCode(); private Format getFormat(final String desc); private int readArgumentIndex(final String pattern, final ParsePosition pos); private String parseFormatDescription(final String pattern, final ParsePosition pos); private String insertFormats(final String pattern, final ArrayList<String> customPatterns); private void seekNonWs(final String pattern, final ParsePosition pos); private ParsePosition next(final ParsePosition pos); private StringBuilder appendQuotedString(final String pattern, final ParsePosition pos, final StringBuilder appendTo, final boolean escapingOn); private void getQuotedString(final String pattern, final ParsePosition pos, final boolean escapingOn); private boolean containsElements(final Collection<?> coll);
198
testBuiltInChoiceFormat
```java // Abstract Java Tested Class package org.apache.commons.lang3.text; import java.text.Format; import java.text.MessageFormat; import java.text.ParsePosition; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Locale; import java.util.Map; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.Validate; public class ExtendedMessageFormat extends MessageFormat { private static final long serialVersionUID = -2362048321261811743L; private static final int HASH_SEED = 31; private static final String DUMMY_PATTERN = ""; private static final String ESCAPED_QUOTE = "''"; private static final char START_FMT = ','; private static final char END_FE = '}'; private static final char START_FE = '{'; private static final char QUOTE = '\''; private String toPattern; private final Map<String, ? extends FormatFactory> registry; public ExtendedMessageFormat(final String pattern); public ExtendedMessageFormat(final String pattern, final Locale locale); public ExtendedMessageFormat(final String pattern, final Map<String, ? extends FormatFactory> registry); public ExtendedMessageFormat(final String pattern, final Locale locale, final Map<String, ? extends FormatFactory> registry); @Override public String toPattern(); @Override public final void applyPattern(final String pattern); @Override public void setFormat(final int formatElementIndex, final Format newFormat); @Override public void setFormatByArgumentIndex(final int argumentIndex, final Format newFormat); @Override public void setFormats(final Format[] newFormats); @Override public void setFormatsByArgumentIndex(final Format[] newFormats); @Override public boolean equals(final Object obj); @Override public int hashCode(); private Format getFormat(final String desc); private int readArgumentIndex(final String pattern, final ParsePosition pos); private String parseFormatDescription(final String pattern, final ParsePosition pos); private String insertFormats(final String pattern, final ArrayList<String> customPatterns); private void seekNonWs(final String pattern, final ParsePosition pos); private ParsePosition next(final ParsePosition pos); private StringBuilder appendQuotedString(final String pattern, final ParsePosition pos, final StringBuilder appendTo, final boolean escapingOn); private void getQuotedString(final String pattern, final ParsePosition pos, final boolean escapingOn); private boolean containsElements(final Collection<?> coll); } // Abstract Java Test Class package org.apache.commons.lang3.text; import org.junit.Test; import org.junit.Before; import static org.junit.Assert.*; import static org.apache.commons.lang3.JavaVersion.JAVA_1_4; import java.text.ChoiceFormat; import java.text.DateFormat; import java.text.FieldPosition; import java.text.Format; import java.text.MessageFormat; import java.text.NumberFormat; import java.text.ParsePosition; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import org.apache.commons.lang3.SystemUtils; public class ExtendedMessageFormatTest { private final Map<String, FormatFactory> registry = new HashMap<String, FormatFactory>(); @Before public void setUp() throws Exception; @Test public void testExtendedFormats(); @Test public void testEscapedQuote_LANG_477(); @Test public void testExtendedAndBuiltInFormats(); @Test public void testBuiltInChoiceFormat(); @Test public void testBuiltInDateTimeFormat(); @Test public void testOverriddenBuiltinFormat(); @Test public void testBuiltInNumberFormat(); @Test public void testEqualsHashcode(); private void checkBuiltInFormat(final String pattern, final Object[] args, final Locale[] locales); private void checkBuiltInFormat(final String pattern, final Map<String, ?> registry, final Object[] args, final Locale[] locales); private void checkBuiltInFormat(final String pattern, final Map<String, ?> registry, final Object[] args, final Locale locale); private void assertPatternsEqual(final String message, final String expected, final String actual); private MessageFormat createMessageFormat(final String pattern, final Locale locale); @Override public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos); @Override public Object parseObject(final String source, final ParsePosition pos); @Override public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos); @Override public Object parseObject(final String source, final ParsePosition pos); @Override public Format getFormat(final String name, final String arguments, final Locale locale); @Override public Format getFormat(final String name, final String arguments, final Locale locale); @Override public Format getFormat(final String name, final String arguments, final Locale locale); public OtherExtendedMessageFormat(final String pattern, final Locale locale, final Map<String, ? extends FormatFactory> registry); } ``` You are a professional Java test case writer, please create a test case named `testBuiltInChoiceFormat` for the `ExtendedMessageFormat` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test the built in choice format. */ // } // } // } // // currently sub-formats not supported // } catch (IllegalArgumentException e) { // assertEquals(highExpected, emf.format(highArgs)); // assertEquals(lowExpected, emf.format(lowArgs)); // String highExpected = highArgs[0] + " HIGH " + cf.format(highArgs[2]); // String lowExpected = lowArgs[0] + " low " + nf.format(lowArgs[2]); // try { // assertPatterns(null, pattern, emf.toPattern()); // } // emf = new ExtendedMessageFormat(pattern, testLocales[i], registry); // cf = NumberFormat.getCurrencyInstance(testLocales[i]); // nf = NumberFormat.getNumberInstance(testLocales[i]); // } else { // emf = new ExtendedMessageFormat(pattern, registry); // cf = NumberFormat.getCurrencyInstance(); // nf = NumberFormat.getNumberInstance(); // if (testLocales[i] == null) { // ExtendedMessageFormat emf = null; // NumberFormat cf = null; // NumberFormat nf = null; // for (int i = 0; i < testLocales.length; i++) { // System.arraycopy(availableLocales, 0, testLocales, 1, availableLocales.length); // testLocales[0] = null; // Locale[] testLocales = new Locale[availableLocales.length + 1]; // Locale[] availableLocales = ChoiceFormat.getAvailableLocales(); // Object[] highArgs = new Object[] {Integer.valueOf(2), "High", Double.valueOf("9876.54")}; // Object[] lowArgs = new Object[] {Integer.valueOf(1), "Low", Double.valueOf("1234.56")}; // String pattern = "Choice: {0,choice,1.0#{0} {1,lower} {2,number}|2.0#{0} {1,upper} {2,number,currency}}"; // public void testExtendedAndBuiltInWithChoiceFormat() { // */ // * NOTE: FAILING - currently sub-formats not supported // * // * Test mixed extended and built-in formats with choice format. // /** // } // } // // currently sub-formats not supported // } catch (IllegalArgumentException e) { // assertEquals("TWO", emf.format(new Object[] {Integer.valueOf(2), "two"})); // assertEquals("one", emf.format(new Object[] {Integer.valueOf(1), "ONE"})); // try { // assertPatterns(null, pattern, emf.toPattern()); // ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry); // String pattern = "Choice: {0,choice,1.0#{1,lower}|2.0#{1,upper}}"; // public void testExtendedWithChoiceFormat() { // */
183
// // Abstract Java Tested Class // package org.apache.commons.lang3.text; // // import java.text.Format; // import java.text.MessageFormat; // import java.text.ParsePosition; // import java.util.ArrayList; // import java.util.Collection; // import java.util.Iterator; // import java.util.Locale; // import java.util.Map; // import org.apache.commons.lang3.ObjectUtils; // import org.apache.commons.lang3.Validate; // // // // public class ExtendedMessageFormat extends MessageFormat { // private static final long serialVersionUID = -2362048321261811743L; // private static final int HASH_SEED = 31; // private static final String DUMMY_PATTERN = ""; // private static final String ESCAPED_QUOTE = "''"; // private static final char START_FMT = ','; // private static final char END_FE = '}'; // private static final char START_FE = '{'; // private static final char QUOTE = '\''; // private String toPattern; // private final Map<String, ? extends FormatFactory> registry; // // public ExtendedMessageFormat(final String pattern); // public ExtendedMessageFormat(final String pattern, final Locale locale); // public ExtendedMessageFormat(final String pattern, final Map<String, ? extends FormatFactory> registry); // public ExtendedMessageFormat(final String pattern, final Locale locale, final Map<String, ? extends FormatFactory> registry); // @Override // public String toPattern(); // @Override // public final void applyPattern(final String pattern); // @Override // public void setFormat(final int formatElementIndex, final Format newFormat); // @Override // public void setFormatByArgumentIndex(final int argumentIndex, final Format newFormat); // @Override // public void setFormats(final Format[] newFormats); // @Override // public void setFormatsByArgumentIndex(final Format[] newFormats); // @Override // public boolean equals(final Object obj); // @Override // public int hashCode(); // private Format getFormat(final String desc); // private int readArgumentIndex(final String pattern, final ParsePosition pos); // private String parseFormatDescription(final String pattern, final ParsePosition pos); // private String insertFormats(final String pattern, final ArrayList<String> customPatterns); // private void seekNonWs(final String pattern, final ParsePosition pos); // private ParsePosition next(final ParsePosition pos); // private StringBuilder appendQuotedString(final String pattern, final ParsePosition pos, // final StringBuilder appendTo, final boolean escapingOn); // private void getQuotedString(final String pattern, final ParsePosition pos, // final boolean escapingOn); // private boolean containsElements(final Collection<?> coll); // } // // // Abstract Java Test Class // package org.apache.commons.lang3.text; // // import org.junit.Test; // import org.junit.Before; // import static org.junit.Assert.*; // import static org.apache.commons.lang3.JavaVersion.JAVA_1_4; // import java.text.ChoiceFormat; // import java.text.DateFormat; // import java.text.FieldPosition; // import java.text.Format; // import java.text.MessageFormat; // import java.text.NumberFormat; // import java.text.ParsePosition; // import java.util.Arrays; // import java.util.Calendar; // import java.util.Collections; // import java.util.HashMap; // import java.util.HashSet; // import java.util.Locale; // import java.util.Map; // import org.apache.commons.lang3.SystemUtils; // // // // public class ExtendedMessageFormatTest { // private final Map<String, FormatFactory> registry = new HashMap<String, FormatFactory>(); // // @Before // public void setUp() throws Exception; // @Test // public void testExtendedFormats(); // @Test // public void testEscapedQuote_LANG_477(); // @Test // public void testExtendedAndBuiltInFormats(); // @Test // public void testBuiltInChoiceFormat(); // @Test // public void testBuiltInDateTimeFormat(); // @Test // public void testOverriddenBuiltinFormat(); // @Test // public void testBuiltInNumberFormat(); // @Test // public void testEqualsHashcode(); // private void checkBuiltInFormat(final String pattern, final Object[] args, final Locale[] locales); // private void checkBuiltInFormat(final String pattern, final Map<String, ?> registry, final Object[] args, final Locale[] locales); // private void checkBuiltInFormat(final String pattern, final Map<String, ?> registry, final Object[] args, final Locale locale); // private void assertPatternsEqual(final String message, final String expected, final String actual); // private MessageFormat createMessageFormat(final String pattern, final Locale locale); // @Override // public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos); // @Override // public Object parseObject(final String source, final ParsePosition pos); // @Override // public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos); // @Override // public Object parseObject(final String source, final ParsePosition pos); // @Override // public Format getFormat(final String name, final String arguments, final Locale locale); // @Override // public Format getFormat(final String name, final String arguments, final Locale locale); // @Override // public Format getFormat(final String name, final String arguments, final Locale locale); // public OtherExtendedMessageFormat(final String pattern, final Locale locale, // final Map<String, ? extends FormatFactory> registry); // } // You are a professional Java test case writer, please create a test case named `testBuiltInChoiceFormat` for the `ExtendedMessageFormat` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test the built in choice format. */ // } // } // } // // currently sub-formats not supported // } catch (IllegalArgumentException e) { // assertEquals(highExpected, emf.format(highArgs)); // assertEquals(lowExpected, emf.format(lowArgs)); // String highExpected = highArgs[0] + " HIGH " + cf.format(highArgs[2]); // String lowExpected = lowArgs[0] + " low " + nf.format(lowArgs[2]); // try { // assertPatterns(null, pattern, emf.toPattern()); // } // emf = new ExtendedMessageFormat(pattern, testLocales[i], registry); // cf = NumberFormat.getCurrencyInstance(testLocales[i]); // nf = NumberFormat.getNumberInstance(testLocales[i]); // } else { // emf = new ExtendedMessageFormat(pattern, registry); // cf = NumberFormat.getCurrencyInstance(); // nf = NumberFormat.getNumberInstance(); // if (testLocales[i] == null) { // ExtendedMessageFormat emf = null; // NumberFormat cf = null; // NumberFormat nf = null; // for (int i = 0; i < testLocales.length; i++) { // System.arraycopy(availableLocales, 0, testLocales, 1, availableLocales.length); // testLocales[0] = null; // Locale[] testLocales = new Locale[availableLocales.length + 1]; // Locale[] availableLocales = ChoiceFormat.getAvailableLocales(); // Object[] highArgs = new Object[] {Integer.valueOf(2), "High", Double.valueOf("9876.54")}; // Object[] lowArgs = new Object[] {Integer.valueOf(1), "Low", Double.valueOf("1234.56")}; // String pattern = "Choice: {0,choice,1.0#{0} {1,lower} {2,number}|2.0#{0} {1,upper} {2,number,currency}}"; // public void testExtendedAndBuiltInWithChoiceFormat() { // */ // * NOTE: FAILING - currently sub-formats not supported // * // * Test mixed extended and built-in formats with choice format. // /** // } // } // // currently sub-formats not supported // } catch (IllegalArgumentException e) { // assertEquals("TWO", emf.format(new Object[] {Integer.valueOf(2), "two"})); // assertEquals("one", emf.format(new Object[] {Integer.valueOf(1), "ONE"})); // try { // assertPatterns(null, pattern, emf.toPattern()); // ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry); // String pattern = "Choice: {0,choice,1.0#{1,lower}|2.0#{1,upper}}"; // public void testExtendedWithChoiceFormat() { // */ // * NOTE: FAILING - currently sub-formats not supported // * // * Test extended formats with choice format. // /** @Test public void testBuiltInChoiceFormat() {
/** * Test the built in choice format. */ // } // } // } // // currently sub-formats not supported // } catch (IllegalArgumentException e) { // assertEquals(highExpected, emf.format(highArgs)); // assertEquals(lowExpected, emf.format(lowArgs)); // String highExpected = highArgs[0] + " HIGH " + cf.format(highArgs[2]); // String lowExpected = lowArgs[0] + " low " + nf.format(lowArgs[2]); // try { // assertPatterns(null, pattern, emf.toPattern()); // } // emf = new ExtendedMessageFormat(pattern, testLocales[i], registry); // cf = NumberFormat.getCurrencyInstance(testLocales[i]); // nf = NumberFormat.getNumberInstance(testLocales[i]); // } else { // emf = new ExtendedMessageFormat(pattern, registry); // cf = NumberFormat.getCurrencyInstance(); // nf = NumberFormat.getNumberInstance(); // if (testLocales[i] == null) { // ExtendedMessageFormat emf = null; // NumberFormat cf = null; // NumberFormat nf = null; // for (int i = 0; i < testLocales.length; i++) { // System.arraycopy(availableLocales, 0, testLocales, 1, availableLocales.length); // testLocales[0] = null; // Locale[] testLocales = new Locale[availableLocales.length + 1]; // Locale[] availableLocales = ChoiceFormat.getAvailableLocales(); // Object[] highArgs = new Object[] {Integer.valueOf(2), "High", Double.valueOf("9876.54")}; // Object[] lowArgs = new Object[] {Integer.valueOf(1), "Low", Double.valueOf("1234.56")}; // String pattern = "Choice: {0,choice,1.0#{0} {1,lower} {2,number}|2.0#{0} {1,upper} {2,number,currency}}"; // public void testExtendedAndBuiltInWithChoiceFormat() { // */ // * NOTE: FAILING - currently sub-formats not supported // * // * Test mixed extended and built-in formats with choice format. // /** // } // } // // currently sub-formats not supported // } catch (IllegalArgumentException e) { // assertEquals("TWO", emf.format(new Object[] {Integer.valueOf(2), "two"})); // assertEquals("one", emf.format(new Object[] {Integer.valueOf(1), "ONE"})); // try { // assertPatterns(null, pattern, emf.toPattern()); // ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry); // String pattern = "Choice: {0,choice,1.0#{1,lower}|2.0#{1,upper}}"; // public void testExtendedWithChoiceFormat() { // */ // * NOTE: FAILING - currently sub-formats not supported // * // * Test extended formats with choice format. // /**
1
org.apache.commons.lang3.text.ExtendedMessageFormat
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.lang3.text; import java.text.Format; import java.text.MessageFormat; import java.text.ParsePosition; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Locale; import java.util.Map; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.Validate; public class ExtendedMessageFormat extends MessageFormat { private static final long serialVersionUID = -2362048321261811743L; private static final int HASH_SEED = 31; private static final String DUMMY_PATTERN = ""; private static final String ESCAPED_QUOTE = "''"; private static final char START_FMT = ','; private static final char END_FE = '}'; private static final char START_FE = '{'; private static final char QUOTE = '\''; private String toPattern; private final Map<String, ? extends FormatFactory> registry; public ExtendedMessageFormat(final String pattern); public ExtendedMessageFormat(final String pattern, final Locale locale); public ExtendedMessageFormat(final String pattern, final Map<String, ? extends FormatFactory> registry); public ExtendedMessageFormat(final String pattern, final Locale locale, final Map<String, ? extends FormatFactory> registry); @Override public String toPattern(); @Override public final void applyPattern(final String pattern); @Override public void setFormat(final int formatElementIndex, final Format newFormat); @Override public void setFormatByArgumentIndex(final int argumentIndex, final Format newFormat); @Override public void setFormats(final Format[] newFormats); @Override public void setFormatsByArgumentIndex(final Format[] newFormats); @Override public boolean equals(final Object obj); @Override public int hashCode(); private Format getFormat(final String desc); private int readArgumentIndex(final String pattern, final ParsePosition pos); private String parseFormatDescription(final String pattern, final ParsePosition pos); private String insertFormats(final String pattern, final ArrayList<String> customPatterns); private void seekNonWs(final String pattern, final ParsePosition pos); private ParsePosition next(final ParsePosition pos); private StringBuilder appendQuotedString(final String pattern, final ParsePosition pos, final StringBuilder appendTo, final boolean escapingOn); private void getQuotedString(final String pattern, final ParsePosition pos, final boolean escapingOn); private boolean containsElements(final Collection<?> coll); } // Abstract Java Test Class package org.apache.commons.lang3.text; import org.junit.Test; import org.junit.Before; import static org.junit.Assert.*; import static org.apache.commons.lang3.JavaVersion.JAVA_1_4; import java.text.ChoiceFormat; import java.text.DateFormat; import java.text.FieldPosition; import java.text.Format; import java.text.MessageFormat; import java.text.NumberFormat; import java.text.ParsePosition; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import org.apache.commons.lang3.SystemUtils; public class ExtendedMessageFormatTest { private final Map<String, FormatFactory> registry = new HashMap<String, FormatFactory>(); @Before public void setUp() throws Exception; @Test public void testExtendedFormats(); @Test public void testEscapedQuote_LANG_477(); @Test public void testExtendedAndBuiltInFormats(); @Test public void testBuiltInChoiceFormat(); @Test public void testBuiltInDateTimeFormat(); @Test public void testOverriddenBuiltinFormat(); @Test public void testBuiltInNumberFormat(); @Test public void testEqualsHashcode(); private void checkBuiltInFormat(final String pattern, final Object[] args, final Locale[] locales); private void checkBuiltInFormat(final String pattern, final Map<String, ?> registry, final Object[] args, final Locale[] locales); private void checkBuiltInFormat(final String pattern, final Map<String, ?> registry, final Object[] args, final Locale locale); private void assertPatternsEqual(final String message, final String expected, final String actual); private MessageFormat createMessageFormat(final String pattern, final Locale locale); @Override public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos); @Override public Object parseObject(final String source, final ParsePosition pos); @Override public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos); @Override public Object parseObject(final String source, final ParsePosition pos); @Override public Format getFormat(final String name, final String arguments, final Locale locale); @Override public Format getFormat(final String name, final String arguments, final Locale locale); @Override public Format getFormat(final String name, final String arguments, final Locale locale); public OtherExtendedMessageFormat(final String pattern, final Locale locale, final Map<String, ? extends FormatFactory> registry); } ``` You are a professional Java test case writer, please create a test case named `testBuiltInChoiceFormat` for the `ExtendedMessageFormat` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test the built in choice format. */ // } // } // } // // currently sub-formats not supported // } catch (IllegalArgumentException e) { // assertEquals(highExpected, emf.format(highArgs)); // assertEquals(lowExpected, emf.format(lowArgs)); // String highExpected = highArgs[0] + " HIGH " + cf.format(highArgs[2]); // String lowExpected = lowArgs[0] + " low " + nf.format(lowArgs[2]); // try { // assertPatterns(null, pattern, emf.toPattern()); // } // emf = new ExtendedMessageFormat(pattern, testLocales[i], registry); // cf = NumberFormat.getCurrencyInstance(testLocales[i]); // nf = NumberFormat.getNumberInstance(testLocales[i]); // } else { // emf = new ExtendedMessageFormat(pattern, registry); // cf = NumberFormat.getCurrencyInstance(); // nf = NumberFormat.getNumberInstance(); // if (testLocales[i] == null) { // ExtendedMessageFormat emf = null; // NumberFormat cf = null; // NumberFormat nf = null; // for (int i = 0; i < testLocales.length; i++) { // System.arraycopy(availableLocales, 0, testLocales, 1, availableLocales.length); // testLocales[0] = null; // Locale[] testLocales = new Locale[availableLocales.length + 1]; // Locale[] availableLocales = ChoiceFormat.getAvailableLocales(); // Object[] highArgs = new Object[] {Integer.valueOf(2), "High", Double.valueOf("9876.54")}; // Object[] lowArgs = new Object[] {Integer.valueOf(1), "Low", Double.valueOf("1234.56")}; // String pattern = "Choice: {0,choice,1.0#{0} {1,lower} {2,number}|2.0#{0} {1,upper} {2,number,currency}}"; // public void testExtendedAndBuiltInWithChoiceFormat() { // */ // * NOTE: FAILING - currently sub-formats not supported // * // * Test mixed extended and built-in formats with choice format. // /** // } // } // // currently sub-formats not supported // } catch (IllegalArgumentException e) { // assertEquals("TWO", emf.format(new Object[] {Integer.valueOf(2), "two"})); // assertEquals("one", emf.format(new Object[] {Integer.valueOf(1), "ONE"})); // try { // assertPatterns(null, pattern, emf.toPattern()); // ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry); // String pattern = "Choice: {0,choice,1.0#{1,lower}|2.0#{1,upper}}"; // public void testExtendedWithChoiceFormat() { // */ // * NOTE: FAILING - currently sub-formats not supported // * // * Test extended formats with choice format. // /** @Test public void testBuiltInChoiceFormat() { ```
public class ExtendedMessageFormat extends MessageFormat
package org.apache.commons.lang3.text; import org.junit.Test; import org.junit.Before; import static org.junit.Assert.*; import static org.apache.commons.lang3.JavaVersion.JAVA_1_4; import java.text.ChoiceFormat; import java.text.DateFormat; import java.text.FieldPosition; import java.text.Format; import java.text.MessageFormat; import java.text.NumberFormat; import java.text.ParsePosition; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import org.apache.commons.lang3.SystemUtils;
@Before public void setUp() throws Exception; @Test public void testExtendedFormats(); @Test public void testEscapedQuote_LANG_477(); @Test public void testExtendedAndBuiltInFormats(); @Test public void testBuiltInChoiceFormat(); @Test public void testBuiltInDateTimeFormat(); @Test public void testOverriddenBuiltinFormat(); @Test public void testBuiltInNumberFormat(); @Test public void testEqualsHashcode(); private void checkBuiltInFormat(final String pattern, final Object[] args, final Locale[] locales); private void checkBuiltInFormat(final String pattern, final Map<String, ?> registry, final Object[] args, final Locale[] locales); private void checkBuiltInFormat(final String pattern, final Map<String, ?> registry, final Object[] args, final Locale locale); private void assertPatternsEqual(final String message, final String expected, final String actual); private MessageFormat createMessageFormat(final String pattern, final Locale locale); @Override public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos); @Override public Object parseObject(final String source, final ParsePosition pos); @Override public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos); @Override public Object parseObject(final String source, final ParsePosition pos); @Override public Format getFormat(final String name, final String arguments, final Locale locale); @Override public Format getFormat(final String name, final String arguments, final Locale locale); @Override public Format getFormat(final String name, final String arguments, final Locale locale); public OtherExtendedMessageFormat(final String pattern, final Locale locale, final Map<String, ? extends FormatFactory> registry);
9f38abb65845d1eee30b3451c58bd495072c16e6e11817f27e5b96159f20abe2
[ "org.apache.commons.lang3.text.ExtendedMessageFormatTest::testBuiltInChoiceFormat" ]
private static final long serialVersionUID = -2362048321261811743L; private static final int HASH_SEED = 31; private static final String DUMMY_PATTERN = ""; private static final String ESCAPED_QUOTE = "''"; private static final char START_FMT = ','; private static final char END_FE = '}'; private static final char START_FE = '{'; private static final char QUOTE = '\''; private String toPattern; private final Map<String, ? extends FormatFactory> registry;
@Test public void testBuiltInChoiceFormat()
private final Map<String, FormatFactory> registry = new HashMap<String, FormatFactory>();
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.text; import org.junit.Test; import org.junit.Before; import static org.junit.Assert.*; import static org.apache.commons.lang3.JavaVersion.JAVA_1_4; import java.text.ChoiceFormat; import java.text.DateFormat; import java.text.FieldPosition; import java.text.Format; import java.text.MessageFormat; import java.text.NumberFormat; import java.text.ParsePosition; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import org.apache.commons.lang3.SystemUtils; /** * Test case for {@link ExtendedMessageFormat}. * * @since 2.4 * @version $Id$ */ public class ExtendedMessageFormatTest { private final Map<String, FormatFactory> registry = new HashMap<String, FormatFactory>(); @Before public void setUp() throws Exception { registry.put("lower", new LowerCaseFormatFactory()); registry.put("upper", new UpperCaseFormatFactory()); } /** * Test extended formats. */ @Test public void testExtendedFormats() { final String pattern = "Lower: {0,lower} Upper: {1,upper}"; final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry); assertPatternsEqual("TOPATTERN", pattern, emf.toPattern()); assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"foo", "bar"})); assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"Foo", "Bar"})); assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"FOO", "BAR"})); assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"FOO", "bar"})); assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"foo", "BAR"})); } /** * Test Bug LANG-477 - out of memory error with escaped quote */ @Test public void testEscapedQuote_LANG_477() { final String pattern = "it''s a {0,lower} 'test'!"; final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry); assertEquals("it's a dummy test!", emf.format(new Object[] {"DUMMY"})); } /** * Test extended and built in formats. */ @Test public void testExtendedAndBuiltInFormats() { final Calendar cal = Calendar.getInstance(); cal.set(2007, Calendar.JANUARY, 23, 18, 33, 05); final Object[] args = new Object[] {"John Doe", cal.getTime(), Double.valueOf("12345.67")}; final String builtinsPattern = "DOB: {1,date,short} Salary: {2,number,currency}"; final String extendedPattern = "Name: {0,upper} "; final String pattern = extendedPattern + builtinsPattern; final HashSet<Locale> testLocales = new HashSet<Locale>(); testLocales.addAll(Arrays.asList(DateFormat.getAvailableLocales())); testLocales.retainAll(Arrays.asList(NumberFormat.getAvailableLocales())); testLocales.add(null); for (final Locale locale : testLocales) { final MessageFormat builtins = createMessageFormat(builtinsPattern, locale); final String expectedPattern = extendedPattern + builtins.toPattern(); DateFormat df = null; NumberFormat nf = null; ExtendedMessageFormat emf = null; if (locale == null) { df = DateFormat.getDateInstance(DateFormat.SHORT); nf = NumberFormat.getCurrencyInstance(); emf = new ExtendedMessageFormat(pattern, registry); } else { df = DateFormat.getDateInstance(DateFormat.SHORT, locale); nf = NumberFormat.getCurrencyInstance(locale); emf = new ExtendedMessageFormat(pattern, locale, registry); } final StringBuilder expected = new StringBuilder(); expected.append("Name: "); expected.append(args[0].toString().toUpperCase()); expected.append(" DOB: "); expected.append(df.format(args[1])); expected.append(" Salary: "); expected.append(nf.format(args[2])); assertPatternsEqual("pattern comparison for locale " + locale, expectedPattern, emf.toPattern()); assertEquals(String.valueOf(locale), expected.toString(), emf.format(args)); } } // /** // * Test extended formats with choice format. // * // * NOTE: FAILING - currently sub-formats not supported // */ // public void testExtendedWithChoiceFormat() { // String pattern = "Choice: {0,choice,1.0#{1,lower}|2.0#{1,upper}}"; // ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry); // assertPatterns(null, pattern, emf.toPattern()); // try { // assertEquals("one", emf.format(new Object[] {Integer.valueOf(1), "ONE"})); // assertEquals("TWO", emf.format(new Object[] {Integer.valueOf(2), "two"})); // } catch (IllegalArgumentException e) { // // currently sub-formats not supported // } // } // /** // * Test mixed extended and built-in formats with choice format. // * // * NOTE: FAILING - currently sub-formats not supported // */ // public void testExtendedAndBuiltInWithChoiceFormat() { // String pattern = "Choice: {0,choice,1.0#{0} {1,lower} {2,number}|2.0#{0} {1,upper} {2,number,currency}}"; // Object[] lowArgs = new Object[] {Integer.valueOf(1), "Low", Double.valueOf("1234.56")}; // Object[] highArgs = new Object[] {Integer.valueOf(2), "High", Double.valueOf("9876.54")}; // Locale[] availableLocales = ChoiceFormat.getAvailableLocales(); // Locale[] testLocales = new Locale[availableLocales.length + 1]; // testLocales[0] = null; // System.arraycopy(availableLocales, 0, testLocales, 1, availableLocales.length); // for (int i = 0; i < testLocales.length; i++) { // NumberFormat nf = null; // NumberFormat cf = null; // ExtendedMessageFormat emf = null; // if (testLocales[i] == null) { // nf = NumberFormat.getNumberInstance(); // cf = NumberFormat.getCurrencyInstance(); // emf = new ExtendedMessageFormat(pattern, registry); // } else { // nf = NumberFormat.getNumberInstance(testLocales[i]); // cf = NumberFormat.getCurrencyInstance(testLocales[i]); // emf = new ExtendedMessageFormat(pattern, testLocales[i], registry); // } // assertPatterns(null, pattern, emf.toPattern()); // try { // String lowExpected = lowArgs[0] + " low " + nf.format(lowArgs[2]); // String highExpected = highArgs[0] + " HIGH " + cf.format(highArgs[2]); // assertEquals(lowExpected, emf.format(lowArgs)); // assertEquals(highExpected, emf.format(highArgs)); // } catch (IllegalArgumentException e) { // // currently sub-formats not supported // } // } // } /** * Test the built in choice format. */ @Test public void testBuiltInChoiceFormat() { final Object[] values = new Number[] {Integer.valueOf(1), Double.valueOf("2.2"), Double.valueOf("1234.5")}; String choicePattern = null; final Locale[] availableLocales = ChoiceFormat.getAvailableLocales(); choicePattern = "{0,choice,1#One|2#Two|3#Many {0,number}}"; for (final Object value : values) { checkBuiltInFormat(value + ": " + choicePattern, new Object[] {value}, availableLocales); } choicePattern = "{0,choice,1#''One''|2#\"Two\"|3#''{Many}'' {0,number}}"; for (final Object value : values) { checkBuiltInFormat(value + ": " + choicePattern, new Object[] {value}, availableLocales); } } /** * Test the built in date/time formats */ @Test public void testBuiltInDateTimeFormat() { final Calendar cal = Calendar.getInstance(); cal.set(2007, Calendar.JANUARY, 23, 18, 33, 05); final Object[] args = new Object[] {cal.getTime()}; final Locale[] availableLocales = DateFormat.getAvailableLocales(); checkBuiltInFormat("1: {0,date,short}", args, availableLocales); checkBuiltInFormat("2: {0,date,medium}", args, availableLocales); checkBuiltInFormat("3: {0,date,long}", args, availableLocales); checkBuiltInFormat("4: {0,date,full}", args, availableLocales); checkBuiltInFormat("5: {0,date,d MMM yy}", args, availableLocales); checkBuiltInFormat("6: {0,time,short}", args, availableLocales); checkBuiltInFormat("7: {0,time,medium}", args, availableLocales); checkBuiltInFormat("8: {0,time,long}", args, availableLocales); checkBuiltInFormat("9: {0,time,full}", args, availableLocales); checkBuiltInFormat("10: {0,time,HH:mm}", args, availableLocales); checkBuiltInFormat("11: {0,date}", args, availableLocales); checkBuiltInFormat("12: {0,time}", args, availableLocales); } @Test public void testOverriddenBuiltinFormat() { final Calendar cal = Calendar.getInstance(); cal.set(2007, Calendar.JANUARY, 23); final Object[] args = new Object[] {cal.getTime()}; final Locale[] availableLocales = DateFormat.getAvailableLocales(); final Map<String, ? extends FormatFactory> registry = Collections.singletonMap("date", new OverrideShortDateFormatFactory()); //check the non-overridden builtins: checkBuiltInFormat("1: {0,date}", registry, args, availableLocales); checkBuiltInFormat("2: {0,date,medium}", registry, args, availableLocales); checkBuiltInFormat("3: {0,date,long}", registry, args, availableLocales); checkBuiltInFormat("4: {0,date,full}", registry, args, availableLocales); checkBuiltInFormat("5: {0,date,d MMM yy}", registry, args, availableLocales); //check the overridden format: for (int i = -1; i < availableLocales.length; i++) { final Locale locale = i < 0 ? null : availableLocales[i]; final MessageFormat dateDefault = createMessageFormat("{0,date}", locale); final String pattern = "{0,date,short}"; final ExtendedMessageFormat dateShort = new ExtendedMessageFormat(pattern, locale, registry); assertEquals("overridden date,short format", dateDefault.format(args), dateShort.format(args)); assertEquals("overridden date,short pattern", pattern, dateShort.toPattern()); } } /** * Test the built in number formats. */ @Test public void testBuiltInNumberFormat() { final Object[] args = new Object[] {Double.valueOf("6543.21")}; final Locale[] availableLocales = NumberFormat.getAvailableLocales(); checkBuiltInFormat("1: {0,number}", args, availableLocales); checkBuiltInFormat("2: {0,number,integer}", args, availableLocales); checkBuiltInFormat("3: {0,number,currency}", args, availableLocales); checkBuiltInFormat("4: {0,number,percent}", args, availableLocales); checkBuiltInFormat("5: {0,number,00000.000}", args, availableLocales); } /** * Test equals() and hashcode. */ @Test public void testEqualsHashcode() { final Map<String, ? extends FormatFactory> registry = Collections.singletonMap("testfmt", new LowerCaseFormatFactory()); final Map<String, ? extends FormatFactory> otherRegitry = Collections.singletonMap("testfmt", new UpperCaseFormatFactory()); final String pattern = "Pattern: {0,testfmt}"; final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, Locale.US, registry); ExtendedMessageFormat other = null; // Same object assertTrue("same, equals()", emf.equals(emf)); assertTrue("same, hashcode()", emf.hashCode() == emf.hashCode()); // Equal Object other = new ExtendedMessageFormat(pattern, Locale.US, registry); assertTrue("equal, equals()", emf.equals(other)); assertTrue("equal, hashcode()", emf.hashCode() == other.hashCode()); // Different Class other = new OtherExtendedMessageFormat(pattern, Locale.US, registry); assertFalse("class, equals()", emf.equals(other)); assertTrue("class, hashcode()", emf.hashCode() == other.hashCode()); // same hashcode // Different pattern other = new ExtendedMessageFormat("X" + pattern, Locale.US, registry); assertFalse("pattern, equals()", emf.equals(other)); assertFalse("pattern, hashcode()", emf.hashCode() == other.hashCode()); // Different registry other = new ExtendedMessageFormat(pattern, Locale.US, otherRegitry); assertFalse("registry, equals()", emf.equals(other)); assertFalse("registry, hashcode()", emf.hashCode() == other.hashCode()); // Different Locale other = new ExtendedMessageFormat(pattern, Locale.FRANCE, registry); assertFalse("locale, equals()", emf.equals(other)); assertTrue("locale, hashcode()", emf.hashCode() == other.hashCode()); // same hashcode } /** * Test a built in format for the specified Locales, plus <code>null</code> Locale. * @param pattern MessageFormat pattern * @param args MessageFormat arguments * @param locales to test */ private void checkBuiltInFormat(final String pattern, final Object[] args, final Locale[] locales) { checkBuiltInFormat(pattern, null, args, locales); } /** * Test a built in format for the specified Locales, plus <code>null</code> Locale. * @param pattern MessageFormat pattern * @param registry FormatFactory registry to use * @param args MessageFormat arguments * @param locales to test */ private void checkBuiltInFormat(final String pattern, final Map<String, ?> registry, final Object[] args, final Locale[] locales) { checkBuiltInFormat(pattern, registry, args, (Locale) null); for (final Locale locale : locales) { checkBuiltInFormat(pattern, registry, args, locale); } } /** * Create an ExtendedMessageFormat for the specified pattern and locale and check the * formated output matches the expected result for the parameters. * @param pattern string * @param registry map * @param args Object[] * @param locale Locale */ private void checkBuiltInFormat(final String pattern, final Map<String, ?> registry, final Object[] args, final Locale locale) { final StringBuilder buffer = new StringBuilder(); buffer.append("Pattern=["); buffer.append(pattern); buffer.append("], locale=["); buffer.append(locale); buffer.append("]"); final MessageFormat mf = createMessageFormat(pattern, locale); // System.out.println(buffer + ", result=[" + mf.format(args) +"]"); ExtendedMessageFormat emf = null; if (locale == null) { emf = new ExtendedMessageFormat(pattern); } else { emf = new ExtendedMessageFormat(pattern, locale); } assertEquals("format " + buffer.toString(), mf.format(args), emf.format(args)); assertPatternsEqual("toPattern " + buffer.toString(), mf.toPattern(), emf.toPattern()); } //can't trust what MessageFormat does with toPattern() pre 1.4: private void assertPatternsEqual(final String message, final String expected, final String actual) { if (SystemUtils.isJavaVersionAtLeast(JAVA_1_4)) { assertEquals(message, expected, actual); } } /** * Replace MessageFormat(String, Locale) constructor (not available until JDK 1.4). * @param pattern string * @param locale Locale * @return MessageFormat */ private MessageFormat createMessageFormat(final String pattern, final Locale locale) { final MessageFormat result = new MessageFormat(pattern); if (locale != null) { result.setLocale(locale); result.applyPattern(pattern); } return result; } // ------------------------ Test Formats ------------------------ /** * {@link Format} implementation which converts to lower case. */ private static class LowerCaseFormat extends Format { @Override public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) { return toAppendTo.append(((String)obj).toLowerCase()); } @Override public Object parseObject(final String source, final ParsePosition pos) {throw new UnsupportedOperationException();} } /** * {@link Format} implementation which converts to upper case. */ private static class UpperCaseFormat extends Format { @Override public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) { return toAppendTo.append(((String)obj).toUpperCase()); } @Override public Object parseObject(final String source, final ParsePosition pos) {throw new UnsupportedOperationException();} } // ------------------------ Test Format Factories --------------- /** * {@link FormatFactory} implementation for lower case format. */ private static class LowerCaseFormatFactory implements FormatFactory { private static final Format LOWER_INSTANCE = new LowerCaseFormat(); @Override public Format getFormat(final String name, final String arguments, final Locale locale) { return LOWER_INSTANCE; } } /** * {@link FormatFactory} implementation for upper case format. */ private static class UpperCaseFormatFactory implements FormatFactory { private static final Format UPPER_INSTANCE = new UpperCaseFormat(); @Override public Format getFormat(final String name, final String arguments, final Locale locale) { return UPPER_INSTANCE; } } /** * {@link FormatFactory} implementation to override date format "short" to "default". */ private static class OverrideShortDateFormatFactory implements FormatFactory { @Override public Format getFormat(final String name, final String arguments, final Locale locale) { return !"short".equals(arguments) ? null : locale == null ? DateFormat .getDateInstance(DateFormat.DEFAULT) : DateFormat .getDateInstance(DateFormat.DEFAULT, locale); } } /** * Alternative ExtendedMessageFormat impl. */ private static class OtherExtendedMessageFormat extends ExtendedMessageFormat { public OtherExtendedMessageFormat(final String pattern, final Locale locale, final Map<String, ? extends FormatFactory> registry) { super(pattern, locale, registry); } } }
[ { "be_test_class_file": "org/apache/commons/lang3/text/ExtendedMessageFormat.java", "be_test_class_name": "org.apache.commons.lang3.text.ExtendedMessageFormat", "be_test_function_name": "applyPattern", "be_test_function_signature": "(Ljava/lang/String;)V", "line_numbers": [ "146", "147", "148", "149", "151", "152", "153", "155", "156", "157", "158", "159", "161", "162", "164", "165", "166", "167", "168", "169", "170", "171", "172", "173", "175", "176", "177", "180", "181", "182", "183", "184", "185", "190", "191", "194", "195", "196", "197", "200", "201", "202", "203", "204", "207", "209" ], "method_line_rate": 0.08695652173913043 }, { "be_test_class_file": "org/apache/commons/lang3/text/ExtendedMessageFormat.java", "be_test_class_name": "org.apache.commons.lang3.text.ExtendedMessageFormat", "be_test_function_name": "toPattern", "be_test_function_signature": "()Ljava/lang/String;", "line_numbers": [ "136" ], "method_line_rate": 1 } ]
public class TestValueInstantiator extends BaseMapTest
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); }
// 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 `testPropertyBasedBeanInstantiator` for the `ValueInstantiator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Unit tests for property-based 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();
445
testPropertyBasedBeanInstantiator
```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 `testPropertyBasedBeanInstantiator` for the `ValueInstantiator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Unit tests for property-based creators /********************************************************** */
420
// 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 `testPropertyBasedBeanInstantiator` for the `ValueInstantiator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /* /********************************************************** /* Unit tests for property-based creators /********************************************************** */ public void testPropertyBasedBeanInstantiator() throws Exception {
/* /********************************************************** /* Unit tests for property-based 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 `testPropertyBasedBeanInstantiator` for the `ValueInstantiator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /* /********************************************************** /* Unit tests for property-based creators /********************************************************** */ public void testPropertyBasedBeanInstantiator() 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);
9f3cf44b025b3cf4bbeee1b3b2230c6fbcb9f258379c44e70fa3efd390c3da8c
[ "com.fasterxml.jackson.databind.deser.creators.TestValueInstantiator::testPropertyBasedBeanInstantiator" ]
public void testPropertyBasedBeanInstantiator() 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": "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": "createFromObjectWith", "be_test_function_signature": "(Lcom/fasterxml/jackson/databind/DeserializationContext;[Lcom/fasterxml/jackson/databind/deser/SettableBeanProperty;Lcom/fasterxml/jackson/databind/deser/impl/PropertyValueBuffer;)Ljava/lang/Object;", "line_numbers": [ "229" ], "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 WeekTests extends TestCase
public void testWeek12005() { Week w1 = new Week(1, 2005); Calendar c1 = Calendar.getInstance( TimeZone.getTimeZone("Europe/London"), Locale.UK); c1.setMinimalDaysInFirstWeek(4); // see Java Bug ID 4960215 assertEquals(1104710400000L, w1.getFirstMillisecond(c1)); assertEquals(1105315199999L, w1.getLastMillisecond(c1)); Calendar c2 = Calendar.getInstance( TimeZone.getTimeZone("Europe/Paris"), Locale.FRANCE); c2.setMinimalDaysInFirstWeek(4); // see Java Bug ID 4960215 assertEquals(1104706800000L, w1.getFirstMillisecond(c2)); assertEquals(1105311599999L, w1.getLastMillisecond(c2)); Calendar c3 = Calendar.getInstance( TimeZone.getTimeZone("America/New_York"), Locale.US); assertEquals(1104037200000L, w1.getFirstMillisecond(c3)); assertEquals(1104641999999L, w1.getLastMillisecond(c3)); }
// // Abstract Java Tested Class // package org.jfree.data.time; // // import java.io.Serializable; // import java.util.Calendar; // import java.util.Date; // import java.util.Locale; // import java.util.TimeZone; // // // // public class Week extends RegularTimePeriod implements Serializable { // private static final long serialVersionUID = 1856387786939865061L; // public static final int FIRST_WEEK_IN_YEAR = 1; // public static final int LAST_WEEK_IN_YEAR = 53; // private short year; // private byte week; // private long firstMillisecond; // private long lastMillisecond; // // public Week(); // public Week(int week, int year); // public Week(int week, Year year); // public Week(Date time); // public Week(Date time, TimeZone zone); // public Week(Date time, TimeZone zone, Locale locale); // public Year getYear(); // public int getYearValue(); // public int getWeek(); // public long getFirstMillisecond(); // public long getLastMillisecond(); // public void peg(Calendar calendar); // public RegularTimePeriod previous(); // public RegularTimePeriod next(); // public long getSerialIndex(); // public long getFirstMillisecond(Calendar calendar); // public long getLastMillisecond(Calendar calendar); // public String toString(); // public boolean equals(Object obj); // public int hashCode(); // public int compareTo(Object o1); // public static Week parseWeek(String s); // private static int findSeparator(String s); // private static Year evaluateAsYear(String s); // private static int stringToWeek(String s); // } // // // 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 java.util.Calendar; // import java.util.Date; // import java.util.GregorianCalendar; // import java.util.Locale; // import java.util.TimeZone; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.data.time.Week; // import org.jfree.data.time.Year; // // // // public class WeekTests extends TestCase { // private Week w1Y1900; // private Week w2Y1900; // private Week w51Y9999; // private Week w52Y9999; // // public static Test suite(); // public WeekTests(String name); // protected void setUp(); // public void testEquals(); // public void testW1Y1900Previous(); // public void testW1Y1900Next(); // public void testW52Y9999Previous(); // public void testW52Y9999Next(); // public void testSerialization(); // public void testHashcode(); // public void testNotCloneable(); // public void testWeek12005(); // public void testWeek532005(); // public void testBug1448828(); // public void testBug1498805(); // public void testGetFirstMillisecond(); // public void testGetFirstMillisecondWithTimeZone(); // public void testGetFirstMillisecondWithCalendar(); // public void testGetLastMillisecond(); // public void testGetLastMillisecondWithTimeZone(); // public void testGetLastMillisecondWithCalendar(); // public void testGetSerialIndex(); // public void testNext(); // public void testGetStart(); // public void testGetEnd(); // public void testConstructor(); // } // You are a professional Java test case writer, please create a test case named `testWeek12005` for the `Week` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * The first week in 2005 should span the range: * * TimeZone | Start Millis | End Millis | Start Date | End Date * -----------------+---------------+---------------+-------------+------------ * Europe/London | 1104710400000 | 1105315199999 | 3-Jan-2005 | 9-Jan-2005 * Europe/Paris | 1104706800000 | 1105311599999 | 3-Jan-2005 | 2-Jan-2005 * America/New_York | 1104037200000 | 1104641999999 | 26-Dec-2004 | 1-Jan-2005 * * In London and Paris, Monday is the first day of the week, while in the * US it is Sunday. * * Previously, we were using these values, but see Java Bug ID 4960215: * * TimeZone | Start Millis | End Millis | Start Date | End Date * -----------------+---------------+---------------+-------------+------------ * Europe/London | 1104105600000 | 1104710399999 | 27-Dec-2004 | 2-Jan-2005 * Europe/Paris | 1104102000000 | 1104706799999 | 27-Dec-2004 | 2-Jan-2005 * America/New_York | 1104037200000 | 1104641999999 | 26-Dec-2004 | 1-Jan-2005 */
tests/org/jfree/data/time/junit/WeekTests.java
package org.jfree.data.time; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone;
public Week(); public Week(int week, int year); public Week(int week, Year year); public Week(Date time); public Week(Date time, TimeZone zone); public Week(Date time, TimeZone zone, Locale locale); public Year getYear(); public int getYearValue(); public int getWeek(); public long getFirstMillisecond(); public long getLastMillisecond(); public void peg(Calendar calendar); public RegularTimePeriod previous(); public RegularTimePeriod next(); public long getSerialIndex(); public long getFirstMillisecond(Calendar calendar); public long getLastMillisecond(Calendar calendar); public String toString(); public boolean equals(Object obj); public int hashCode(); public int compareTo(Object o1); public static Week parseWeek(String s); private static int findSeparator(String s); private static Year evaluateAsYear(String s); private static int stringToWeek(String s);
250
testWeek12005
```java // Abstract Java Tested Class package org.jfree.data.time; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class Week extends RegularTimePeriod implements Serializable { private static final long serialVersionUID = 1856387786939865061L; public static final int FIRST_WEEK_IN_YEAR = 1; public static final int LAST_WEEK_IN_YEAR = 53; private short year; private byte week; private long firstMillisecond; private long lastMillisecond; public Week(); public Week(int week, int year); public Week(int week, Year year); public Week(Date time); public Week(Date time, TimeZone zone); public Week(Date time, TimeZone zone, Locale locale); public Year getYear(); public int getYearValue(); public int getWeek(); public long getFirstMillisecond(); public long getLastMillisecond(); public void peg(Calendar calendar); public RegularTimePeriod previous(); public RegularTimePeriod next(); public long getSerialIndex(); public long getFirstMillisecond(Calendar calendar); public long getLastMillisecond(Calendar calendar); public String toString(); public boolean equals(Object obj); public int hashCode(); public int compareTo(Object o1); public static Week parseWeek(String s); private static int findSeparator(String s); private static Year evaluateAsYear(String s); private static int stringToWeek(String s); } // 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 java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.time.Week; import org.jfree.data.time.Year; public class WeekTests extends TestCase { private Week w1Y1900; private Week w2Y1900; private Week w51Y9999; private Week w52Y9999; public static Test suite(); public WeekTests(String name); protected void setUp(); public void testEquals(); public void testW1Y1900Previous(); public void testW1Y1900Next(); public void testW52Y9999Previous(); public void testW52Y9999Next(); public void testSerialization(); public void testHashcode(); public void testNotCloneable(); public void testWeek12005(); public void testWeek532005(); public void testBug1448828(); public void testBug1498805(); public void testGetFirstMillisecond(); public void testGetFirstMillisecondWithTimeZone(); public void testGetFirstMillisecondWithCalendar(); public void testGetLastMillisecond(); public void testGetLastMillisecondWithTimeZone(); public void testGetLastMillisecondWithCalendar(); public void testGetSerialIndex(); public void testNext(); public void testGetStart(); public void testGetEnd(); public void testConstructor(); } ``` You are a professional Java test case writer, please create a test case named `testWeek12005` for the `Week` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * The first week in 2005 should span the range: * * TimeZone | Start Millis | End Millis | Start Date | End Date * -----------------+---------------+---------------+-------------+------------ * Europe/London | 1104710400000 | 1105315199999 | 3-Jan-2005 | 9-Jan-2005 * Europe/Paris | 1104706800000 | 1105311599999 | 3-Jan-2005 | 2-Jan-2005 * America/New_York | 1104037200000 | 1104641999999 | 26-Dec-2004 | 1-Jan-2005 * * In London and Paris, Monday is the first day of the week, while in the * US it is Sunday. * * Previously, we were using these values, but see Java Bug ID 4960215: * * TimeZone | Start Millis | End Millis | Start Date | End Date * -----------------+---------------+---------------+-------------+------------ * Europe/London | 1104105600000 | 1104710399999 | 27-Dec-2004 | 2-Jan-2005 * Europe/Paris | 1104102000000 | 1104706799999 | 27-Dec-2004 | 2-Jan-2005 * America/New_York | 1104037200000 | 1104641999999 | 26-Dec-2004 | 1-Jan-2005 */
234
// // Abstract Java Tested Class // package org.jfree.data.time; // // import java.io.Serializable; // import java.util.Calendar; // import java.util.Date; // import java.util.Locale; // import java.util.TimeZone; // // // // public class Week extends RegularTimePeriod implements Serializable { // private static final long serialVersionUID = 1856387786939865061L; // public static final int FIRST_WEEK_IN_YEAR = 1; // public static final int LAST_WEEK_IN_YEAR = 53; // private short year; // private byte week; // private long firstMillisecond; // private long lastMillisecond; // // public Week(); // public Week(int week, int year); // public Week(int week, Year year); // public Week(Date time); // public Week(Date time, TimeZone zone); // public Week(Date time, TimeZone zone, Locale locale); // public Year getYear(); // public int getYearValue(); // public int getWeek(); // public long getFirstMillisecond(); // public long getLastMillisecond(); // public void peg(Calendar calendar); // public RegularTimePeriod previous(); // public RegularTimePeriod next(); // public long getSerialIndex(); // public long getFirstMillisecond(Calendar calendar); // public long getLastMillisecond(Calendar calendar); // public String toString(); // public boolean equals(Object obj); // public int hashCode(); // public int compareTo(Object o1); // public static Week parseWeek(String s); // private static int findSeparator(String s); // private static Year evaluateAsYear(String s); // private static int stringToWeek(String s); // } // // // 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 java.util.Calendar; // import java.util.Date; // import java.util.GregorianCalendar; // import java.util.Locale; // import java.util.TimeZone; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.data.time.Week; // import org.jfree.data.time.Year; // // // // public class WeekTests extends TestCase { // private Week w1Y1900; // private Week w2Y1900; // private Week w51Y9999; // private Week w52Y9999; // // public static Test suite(); // public WeekTests(String name); // protected void setUp(); // public void testEquals(); // public void testW1Y1900Previous(); // public void testW1Y1900Next(); // public void testW52Y9999Previous(); // public void testW52Y9999Next(); // public void testSerialization(); // public void testHashcode(); // public void testNotCloneable(); // public void testWeek12005(); // public void testWeek532005(); // public void testBug1448828(); // public void testBug1498805(); // public void testGetFirstMillisecond(); // public void testGetFirstMillisecondWithTimeZone(); // public void testGetFirstMillisecondWithCalendar(); // public void testGetLastMillisecond(); // public void testGetLastMillisecondWithTimeZone(); // public void testGetLastMillisecondWithCalendar(); // public void testGetSerialIndex(); // public void testNext(); // public void testGetStart(); // public void testGetEnd(); // public void testConstructor(); // } // You are a professional Java test case writer, please create a test case named `testWeek12005` for the `Week` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * The first week in 2005 should span the range: * * TimeZone | Start Millis | End Millis | Start Date | End Date * -----------------+---------------+---------------+-------------+------------ * Europe/London | 1104710400000 | 1105315199999 | 3-Jan-2005 | 9-Jan-2005 * Europe/Paris | 1104706800000 | 1105311599999 | 3-Jan-2005 | 2-Jan-2005 * America/New_York | 1104037200000 | 1104641999999 | 26-Dec-2004 | 1-Jan-2005 * * In London and Paris, Monday is the first day of the week, while in the * US it is Sunday. * * Previously, we were using these values, but see Java Bug ID 4960215: * * TimeZone | Start Millis | End Millis | Start Date | End Date * -----------------+---------------+---------------+-------------+------------ * Europe/London | 1104105600000 | 1104710399999 | 27-Dec-2004 | 2-Jan-2005 * Europe/Paris | 1104102000000 | 1104706799999 | 27-Dec-2004 | 2-Jan-2005 * America/New_York | 1104037200000 | 1104641999999 | 26-Dec-2004 | 1-Jan-2005 */ public void testWeek12005() {
/** * The first week in 2005 should span the range: * * TimeZone | Start Millis | End Millis | Start Date | End Date * -----------------+---------------+---------------+-------------+------------ * Europe/London | 1104710400000 | 1105315199999 | 3-Jan-2005 | 9-Jan-2005 * Europe/Paris | 1104706800000 | 1105311599999 | 3-Jan-2005 | 2-Jan-2005 * America/New_York | 1104037200000 | 1104641999999 | 26-Dec-2004 | 1-Jan-2005 * * In London and Paris, Monday is the first day of the week, while in the * US it is Sunday. * * Previously, we were using these values, but see Java Bug ID 4960215: * * TimeZone | Start Millis | End Millis | Start Date | End Date * -----------------+---------------+---------------+-------------+------------ * Europe/London | 1104105600000 | 1104710399999 | 27-Dec-2004 | 2-Jan-2005 * Europe/Paris | 1104102000000 | 1104706799999 | 27-Dec-2004 | 2-Jan-2005 * America/New_York | 1104037200000 | 1104641999999 | 26-Dec-2004 | 1-Jan-2005 */
1
org.jfree.data.time.Week
tests
```java // Abstract Java Tested Class package org.jfree.data.time; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class Week extends RegularTimePeriod implements Serializable { private static final long serialVersionUID = 1856387786939865061L; public static final int FIRST_WEEK_IN_YEAR = 1; public static final int LAST_WEEK_IN_YEAR = 53; private short year; private byte week; private long firstMillisecond; private long lastMillisecond; public Week(); public Week(int week, int year); public Week(int week, Year year); public Week(Date time); public Week(Date time, TimeZone zone); public Week(Date time, TimeZone zone, Locale locale); public Year getYear(); public int getYearValue(); public int getWeek(); public long getFirstMillisecond(); public long getLastMillisecond(); public void peg(Calendar calendar); public RegularTimePeriod previous(); public RegularTimePeriod next(); public long getSerialIndex(); public long getFirstMillisecond(Calendar calendar); public long getLastMillisecond(Calendar calendar); public String toString(); public boolean equals(Object obj); public int hashCode(); public int compareTo(Object o1); public static Week parseWeek(String s); private static int findSeparator(String s); private static Year evaluateAsYear(String s); private static int stringToWeek(String s); } // 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 java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.time.Week; import org.jfree.data.time.Year; public class WeekTests extends TestCase { private Week w1Y1900; private Week w2Y1900; private Week w51Y9999; private Week w52Y9999; public static Test suite(); public WeekTests(String name); protected void setUp(); public void testEquals(); public void testW1Y1900Previous(); public void testW1Y1900Next(); public void testW52Y9999Previous(); public void testW52Y9999Next(); public void testSerialization(); public void testHashcode(); public void testNotCloneable(); public void testWeek12005(); public void testWeek532005(); public void testBug1448828(); public void testBug1498805(); public void testGetFirstMillisecond(); public void testGetFirstMillisecondWithTimeZone(); public void testGetFirstMillisecondWithCalendar(); public void testGetLastMillisecond(); public void testGetLastMillisecondWithTimeZone(); public void testGetLastMillisecondWithCalendar(); public void testGetSerialIndex(); public void testNext(); public void testGetStart(); public void testGetEnd(); public void testConstructor(); } ``` You are a professional Java test case writer, please create a test case named `testWeek12005` for the `Week` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * The first week in 2005 should span the range: * * TimeZone | Start Millis | End Millis | Start Date | End Date * -----------------+---------------+---------------+-------------+------------ * Europe/London | 1104710400000 | 1105315199999 | 3-Jan-2005 | 9-Jan-2005 * Europe/Paris | 1104706800000 | 1105311599999 | 3-Jan-2005 | 2-Jan-2005 * America/New_York | 1104037200000 | 1104641999999 | 26-Dec-2004 | 1-Jan-2005 * * In London and Paris, Monday is the first day of the week, while in the * US it is Sunday. * * Previously, we were using these values, but see Java Bug ID 4960215: * * TimeZone | Start Millis | End Millis | Start Date | End Date * -----------------+---------------+---------------+-------------+------------ * Europe/London | 1104105600000 | 1104710399999 | 27-Dec-2004 | 2-Jan-2005 * Europe/Paris | 1104102000000 | 1104706799999 | 27-Dec-2004 | 2-Jan-2005 * America/New_York | 1104037200000 | 1104641999999 | 26-Dec-2004 | 1-Jan-2005 */ public void testWeek12005() { ```
public class Week extends RegularTimePeriod implements 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 java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.time.Week; import org.jfree.data.time.Year;
public static Test suite(); public WeekTests(String name); protected void setUp(); public void testEquals(); public void testW1Y1900Previous(); public void testW1Y1900Next(); public void testW52Y9999Previous(); public void testW52Y9999Next(); public void testSerialization(); public void testHashcode(); public void testNotCloneable(); public void testWeek12005(); public void testWeek532005(); public void testBug1448828(); public void testBug1498805(); public void testGetFirstMillisecond(); public void testGetFirstMillisecondWithTimeZone(); public void testGetFirstMillisecondWithCalendar(); public void testGetLastMillisecond(); public void testGetLastMillisecondWithTimeZone(); public void testGetLastMillisecondWithCalendar(); public void testGetSerialIndex(); public void testNext(); public void testGetStart(); public void testGetEnd(); public void testConstructor();
9f45b7b90decae7f37a9c8ed04acfbcb5013b5e9878c10fc262f99df3cc2a0f7
[ "org.jfree.data.time.junit.WeekTests::testWeek12005" ]
private static final long serialVersionUID = 1856387786939865061L; public static final int FIRST_WEEK_IN_YEAR = 1; public static final int LAST_WEEK_IN_YEAR = 53; private short year; private byte week; private long firstMillisecond; private long lastMillisecond;
public void testWeek12005()
private Week w1Y1900; private Week w2Y1900; private Week w51Y9999; private Week w52Y9999;
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.] * * -------------- * WeekTests.java * -------------- * (C) Copyright 2002-2009, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 05-Apr-2002 : Version 1 (DG); * 26-Jun-2002 : Removed unnecessary imports (DG); * 17-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 13-Mar-2003 : Added serialization test (DG); * 21-Oct-2003 : Added hashCode test (DG); * 06-Apr-2006 : Added testBug1448828() method (DG); * 01-Jun-2006 : Added testBug1498805() method (DG); * 11-Jul-2007 : Fixed bad time zone assumption (DG); * 28-Aug-2007 : Added test for constructor problem (DG); * 19-Dec-2007 : Set default locale for tests that are sensitive * to the locale (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 java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.time.Week; import org.jfree.data.time.Year; /** * Tests for the {@link Week} class. */ public class WeekTests extends TestCase { /** A week. */ private Week w1Y1900; /** A week. */ private Week w2Y1900; /** A week. */ private Week w51Y9999; /** A week. */ private Week w52Y9999; /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(WeekTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public WeekTests(String name) { super(name); } /** * Common test setup. */ protected void setUp() { this.w1Y1900 = new Week(1, 1900); this.w2Y1900 = new Week(2, 1900); this.w51Y9999 = new Week(51, 9999); this.w52Y9999 = new Week(52, 9999); } /** * Tests the equals method. */ public void testEquals() { Week w1 = new Week(1, 2002); Week w2 = new Week(1, 2002); assertTrue(w1.equals(w2)); assertTrue(w2.equals(w1)); w1 = new Week(2, 2002); assertFalse(w1.equals(w2)); w2 = new Week(2, 2002); assertTrue(w1.equals(w2)); w1 = new Week(2, 2003); assertFalse(w1.equals(w2)); w2 = new Week(2, 2003); assertTrue(w1.equals(w2)); } /** * Request the week before week 1, 1900: it should be <code>null</code>. */ public void testW1Y1900Previous() { Week previous = (Week) this.w1Y1900.previous(); assertNull(previous); } /** * Request the week after week 1, 1900: it should be week 2, 1900. */ public void testW1Y1900Next() { Week next = (Week) this.w1Y1900.next(); assertEquals(this.w2Y1900, next); } /** * Request the week before w52, 9999: it should be week 51, 9999. */ public void testW52Y9999Previous() { Week previous = (Week) this.w52Y9999.previous(); assertEquals(this.w51Y9999, previous); } /** * Request the week after w52, 9999: it should be <code>null</code>. */ public void testW52Y9999Next() { Week next = (Week) this.w52Y9999.next(); assertNull(next); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { Week w1 = new Week(24, 1999); Week w2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(w1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); w2 = (Week) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(w1, w2); } /** * Two objects that are equal are required to return the same hashCode. */ public void testHashcode() { Week w1 = new Week(2, 2003); Week w2 = new Week(2, 2003); assertTrue(w1.equals(w2)); int h1 = w1.hashCode(); int h2 = w2.hashCode(); assertEquals(h1, h2); } /** * The {@link Week} class is immutable, so should not be {@link Cloneable}. */ public void testNotCloneable() { Week w = new Week(1, 1999); assertFalse(w instanceof Cloneable); } /** * The first week in 2005 should span the range: * * TimeZone | Start Millis | End Millis | Start Date | End Date * -----------------+---------------+---------------+-------------+------------ * Europe/London | 1104710400000 | 1105315199999 | 3-Jan-2005 | 9-Jan-2005 * Europe/Paris | 1104706800000 | 1105311599999 | 3-Jan-2005 | 2-Jan-2005 * America/New_York | 1104037200000 | 1104641999999 | 26-Dec-2004 | 1-Jan-2005 * * In London and Paris, Monday is the first day of the week, while in the * US it is Sunday. * * Previously, we were using these values, but see Java Bug ID 4960215: * * TimeZone | Start Millis | End Millis | Start Date | End Date * -----------------+---------------+---------------+-------------+------------ * Europe/London | 1104105600000 | 1104710399999 | 27-Dec-2004 | 2-Jan-2005 * Europe/Paris | 1104102000000 | 1104706799999 | 27-Dec-2004 | 2-Jan-2005 * America/New_York | 1104037200000 | 1104641999999 | 26-Dec-2004 | 1-Jan-2005 */ public void testWeek12005() { Week w1 = new Week(1, 2005); Calendar c1 = Calendar.getInstance( TimeZone.getTimeZone("Europe/London"), Locale.UK); c1.setMinimalDaysInFirstWeek(4); // see Java Bug ID 4960215 assertEquals(1104710400000L, w1.getFirstMillisecond(c1)); assertEquals(1105315199999L, w1.getLastMillisecond(c1)); Calendar c2 = Calendar.getInstance( TimeZone.getTimeZone("Europe/Paris"), Locale.FRANCE); c2.setMinimalDaysInFirstWeek(4); // see Java Bug ID 4960215 assertEquals(1104706800000L, w1.getFirstMillisecond(c2)); assertEquals(1105311599999L, w1.getLastMillisecond(c2)); Calendar c3 = Calendar.getInstance( TimeZone.getTimeZone("America/New_York"), Locale.US); assertEquals(1104037200000L, w1.getFirstMillisecond(c3)); assertEquals(1104641999999L, w1.getLastMillisecond(c3)); } /** * The 53rd week in 2004 in London and Paris should span the range: * * TimeZone | Start Millis | End Millis | Start Date | End Date * -----------------+---------------+---------------+-------------+------------ * Europe/London | 1104105600000 | 1104710399999 | 27-Dec-2004 | 02-Jan-2005 * Europe/Paris | 1104102000000 | 1104706799999 | 27-Dec-2004 | 02-Jan-2005 * * The 53rd week in 2005 in New York should span the range: * * TimeZone | Start Millis | End Millis | Start Date | End Date * -----------------+---------------+---------------+-------------+------------ * America/New_York | 1135486800000 | 1136091599999 | 25-Dec-2005 | 31-Dec-2005 * * In London and Paris, Monday is the first day of the week, while in the * US it is Sunday. */ public void testWeek532005() { Week w1 = new Week(53, 2004); Calendar c1 = Calendar.getInstance( TimeZone.getTimeZone("Europe/London"), Locale.UK); c1.setMinimalDaysInFirstWeek(4); // see Java Bug ID 4960215 assertEquals(1104105600000L, w1.getFirstMillisecond(c1)); assertEquals(1104710399999L, w1.getLastMillisecond(c1)); Calendar c2 = Calendar.getInstance( TimeZone.getTimeZone("Europe/Paris"), Locale.FRANCE); c2.setMinimalDaysInFirstWeek(4); // see Java Bug ID 4960215 assertEquals(1104102000000L, w1.getFirstMillisecond(c2)); assertEquals(1104706799999L, w1.getLastMillisecond(c2)); w1 = new Week(53, 2005); Calendar c3 = Calendar.getInstance( TimeZone.getTimeZone("America/New_York"), Locale.US); assertEquals(1135486800000L, w1.getFirstMillisecond(c3)); assertEquals(1136091599999L, w1.getLastMillisecond(c3)); } /** * A test case for bug 1448828. */ public void testBug1448828() { Locale saved = Locale.getDefault(); Locale.setDefault(Locale.UK); try { Week w = new Week(new Date(1136109830000l), TimeZone.getTimeZone("GMT"), Locale.getDefault()); assertEquals(2005, w.getYearValue()); assertEquals(52, w.getWeek()); } finally { Locale.setDefault(saved); } } /** * A test case for bug 1498805. */ public void testBug1498805() { Locale saved = Locale.getDefault(); Locale.setDefault(Locale.UK); try { TimeZone zone = TimeZone.getTimeZone("GMT"); GregorianCalendar gc = new GregorianCalendar(zone); gc.set(2005, Calendar.JANUARY, 1, 12, 0, 0); Week w = new Week(gc.getTime(), zone, Locale.getDefault()); assertEquals(53, w.getWeek()); assertEquals(new Year(2004), w.getYear()); } finally { Locale.setDefault(saved); } } /** * Some checks for the getFirstMillisecond() method. */ public void testGetFirstMillisecond() { Locale saved = Locale.getDefault(); Locale.setDefault(Locale.UK); TimeZone savedZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Week w = new Week(3, 1970); assertEquals(946800000L, w.getFirstMillisecond()); Locale.setDefault(saved); TimeZone.setDefault(savedZone); } /** * Some checks for the getFirstMillisecond(TimeZone) method. */ public void testGetFirstMillisecondWithTimeZone() { Week w = new Week(47, 1950); Locale saved = Locale.getDefault(); Locale.setDefault(Locale.US); try { TimeZone zone = TimeZone.getTimeZone("America/Los_Angeles"); Calendar c = new GregorianCalendar(zone); assertEquals(-603302400000L, w.getFirstMillisecond(c)); } finally { Locale.setDefault(saved); } // try null calendar boolean pass = false; try { w.getFirstMillisecond((Calendar) null); } catch (NullPointerException e) { pass = true; } assertTrue(pass); } /** * Some checks for the getFirstMillisecond(TimeZone) method. */ public void testGetFirstMillisecondWithCalendar() { Week w = new Week(1, 2001); GregorianCalendar calendar = new GregorianCalendar(Locale.GERMANY); calendar.setTimeZone(TimeZone.getTimeZone("Europe/Frankfurt")); assertEquals(978307200000L, w.getFirstMillisecond(calendar)); // try null calendar boolean pass = false; try { w.getFirstMillisecond((Calendar) null); } catch (NullPointerException e) { pass = true; } assertTrue(pass); } /** * Some checks for the getLastMillisecond() method. */ public void testGetLastMillisecond() { Locale saved = Locale.getDefault(); Locale.setDefault(Locale.UK); TimeZone savedZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Week w = new Week(31, 1970); assertEquals(18485999999L, w.getLastMillisecond()); Locale.setDefault(saved); TimeZone.setDefault(savedZone); } /** * Some checks for the getLastMillisecond(TimeZone) method. */ public void testGetLastMillisecondWithTimeZone() { Week w = new Week(2, 1950); Locale saved = Locale.getDefault(); Locale.setDefault(Locale.US); try { TimeZone zone = TimeZone.getTimeZone("America/Los_Angeles"); Calendar c = new GregorianCalendar(zone); assertEquals(-629913600001L, w.getLastMillisecond(c)); } finally { Locale.setDefault(saved); } // try null calendar boolean pass = false; try { w.getLastMillisecond((Calendar) null); } catch (NullPointerException e) { pass = true; } assertTrue(pass); } /** * Some checks for the getLastMillisecond(TimeZone) method. */ public void testGetLastMillisecondWithCalendar() { Week w = new Week(52, 2001); GregorianCalendar calendar = new GregorianCalendar(Locale.GERMANY); calendar.setTimeZone(TimeZone.getTimeZone("Europe/Frankfurt")); assertEquals(1009756799999L, w.getLastMillisecond(calendar)); // try null calendar boolean pass = false; try { w.getLastMillisecond((Calendar) null); } catch (NullPointerException e) { pass = true; } assertTrue(pass); } /** * Some checks for the getSerialIndex() method. */ public void testGetSerialIndex() { Week w = new Week(1, 2000); assertEquals(106001L, w.getSerialIndex()); w = new Week(1, 1900); assertEquals(100701L, w.getSerialIndex()); } /** * Some checks for the testNext() method. */ public void testNext() { Week w = new Week(12, 2000); w = (Week) w.next(); assertEquals(new Year(2000), w.getYear()); assertEquals(13, w.getWeek()); w = new Week(53, 9999); assertNull(w.next()); } /** * Some checks for the getStart() method. */ public void testGetStart() { Locale saved = Locale.getDefault(); Locale.setDefault(Locale.ITALY); Calendar cal = Calendar.getInstance(Locale.ITALY); cal.set(2006, Calendar.JANUARY, 16, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Week w = new Week(3, 2006); assertEquals(cal.getTime(), w.getStart()); Locale.setDefault(saved); } /** * Some checks for the getEnd() method. */ public void testGetEnd() { Locale saved = Locale.getDefault(); Locale.setDefault(Locale.ITALY); Calendar cal = Calendar.getInstance(Locale.ITALY); cal.set(2006, Calendar.JANUARY, 8, 23, 59, 59); cal.set(Calendar.MILLISECOND, 999); Week w = new Week(1, 2006); assertEquals(cal.getTime(), w.getEnd()); Locale.setDefault(saved); } /** * A test for a problem in constructing a new Week instance. */ public void testConstructor() { Locale savedLocale = Locale.getDefault(); TimeZone savedZone = TimeZone.getDefault(); Locale.setDefault(new Locale("da", "DK")); TimeZone.setDefault(TimeZone.getTimeZone("Europe/Copenhagen")); GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance( TimeZone.getDefault(), Locale.getDefault()); // first day of week is monday assertEquals(Calendar.MONDAY, cal.getFirstDayOfWeek()); cal.set(2007, Calendar.AUGUST, 26, 1, 0, 0); cal.set(Calendar.MILLISECOND, 0); Date t = cal.getTime(); Week w = new Week(t, TimeZone.getTimeZone("Europe/Copenhagen"), Locale.getDefault()); assertEquals(34, w.getWeek()); Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("US/Detroit")); cal = (GregorianCalendar) Calendar.getInstance(TimeZone.getDefault()); // first day of week is Sunday assertEquals(Calendar.SUNDAY, cal.getFirstDayOfWeek()); cal.set(2007, Calendar.AUGUST, 26, 1, 0, 0); cal.set(Calendar.MILLISECOND, 0); t = cal.getTime(); w = new Week(t, TimeZone.getTimeZone("Europe/Copenhagen"), Locale.getDefault()); assertEquals(35, w.getWeek()); w = new Week(t, TimeZone.getTimeZone("Europe/Copenhagen"), new Locale("da", "DK")); assertEquals(34, w.getWeek()); Locale.setDefault(savedLocale); TimeZone.setDefault(savedZone); } }
[ { "be_test_class_file": "org/jfree/data/time/Week.java", "be_test_class_name": "org.jfree.data.time.Week", "be_test_function_name": "getFirstMillisecond", "be_test_function_signature": "(Ljava/util/Calendar;)J", "line_numbers": [ "385", "386", "387", "388", "389", "390", "391", "392", "393", "395" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/Week.java", "be_test_class_name": "org.jfree.data.time.Week", "be_test_function_name": "getLastMillisecond", "be_test_function_signature": "(Ljava/util/Calendar;)J", "line_numbers": [ "410", "411", "412", "413", "414", "415", "416", "417", "418", "420" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/time/Week.java", "be_test_class_name": "org.jfree.data.time.Week", "be_test_function_name": "peg", "be_test_function_signature": "(Ljava/util/Calendar;)V", "line_numbers": [ "293", "294", "295" ], "method_line_rate": 1 } ]
public class CSVParserTest
@Test public void testGetOneLineOneParser() throws IOException { final CSVFormat format = CSVFormat.DEFAULT; try (final PipedWriter writer = new PipedWriter(); final CSVParser parser = new CSVParser(new PipedReader(writer), format)) { writer.append(CSV_INPUT_1); writer.append(format.getRecordSeparator()); final CSVRecord record1 = parser.nextRecord(); assertArrayEquals(RESULT[0], record1.values()); writer.append(CSV_INPUT_2); writer.append(format.getRecordSeparator()); final CSVRecord record2 = parser.nextRecord(); assertArrayEquals(RESULT[1], record2.values()); } }
// + " \"foo\n,,\n\"\",,\n\"\"\",d,e\n"; // private static final String CSV_INPUT_1 = "a,b,c,d"; // private static final String CSV_INPUT_2 = "a,b,1 2"; // private static final String[][] RESULT = { { "a", "b", "c", "d" }, { "a", "b", "1 2" }, { "foo baar", "b", "" }, // { "foo\n,,\n\",,\n\"", "d", "e" } }; // // private BOMInputStream createBOMInputStream(final String resource) throws IOException; // @Test // public void testBackslashEscaping() throws IOException; // @Test // public void testBackslashEscaping2() throws IOException; // @Test // @Ignore // public void testBackslashEscapingOld() throws IOException; // @Test // @Ignore("CSV-107") // public void testBOM() throws IOException; // @Test // public void testBOMInputStream_ParserWithReader(); // @Test // public void testBOMInputStream_parseWithReader(); // @Test // public void testBOMInputStream_ParserWithInputStream(); // @Test // public void testCarriageReturnEndings() throws IOException; // @Test // public void testCarriageReturnLineFeedEndings() throws IOException; // @Test // public void testFirstEndOfLineCrLf() throws IOException; // @Test // public void testFirstEndOfLineLf() throws IOException; // @Test // public void testFirstEndOfLineCr() throws IOException; // @Test(expected = NoSuchElementException.class) // public void testClose() throws Exception; // @Test // public void testCSV57() throws Exception; // @Test // public void testDefaultFormat() throws IOException; // @Test(expected = IllegalArgumentException.class) // public void testDuplicateHeaders() throws Exception; // @Test // public void testEmptyFile() throws Exception; // @Test // public void testEmptyLineBehaviourCSV() throws Exception; // @Test // public void testEmptyLineBehaviourExcel() throws Exception; // @Test // public void testEndOfFileBehaviorCSV() throws Exception; // @Test // public void testEndOfFileBehaviourExcel() throws Exception; // @Test // public void testExcelFormat1() throws IOException; // @Test // public void testExcelFormat2() throws Exception; // @Test // public void testExcelHeaderCountLessThanData() throws Exception; // @Test // public void testForEach() throws Exception; // @Test // public void testGetHeaderMap() throws Exception; // @Test // public void testGetLine() throws IOException; // @Test // public void testGetLineNumberWithCR() throws Exception; // @Test // public void testGetLineNumberWithCRLF() throws Exception; // @Test // public void testGetLineNumberWithLF() throws Exception; // @Test // public void testGetOneLine() throws IOException; // @Test // public void testGetOneLineOneParser() throws IOException; // @Test // public void testGetRecordNumberWithCR() throws Exception; // @Test // public void testGetRecordNumberWithCRLF() throws Exception; // @Test // public void testGetRecordNumberWithLF() throws Exception; // @Test // public void testGetRecordPositionWithCRLF() throws Exception; // @Test // public void testGetRecordPositionWithLF() throws Exception; // @Test // public void testGetRecords() throws IOException; // @Test // public void testGetRecordWithMultiLineValues() throws Exception; // @Test // public void testHeader() throws Exception; // @Test // public void testHeaderComment() throws Exception; // @Test // public void testHeaderMissing() throws Exception; // @Test // public void testHeaderMissingWithNull() throws Exception; // @Test // public void testHeadersMissing() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testHeadersMissingException() throws Exception; // @Test // public void testIgnoreCaseHeaderMapping() throws Exception; // @Test // public void testIgnoreEmptyLines() throws IOException; // @Test(expected = IllegalArgumentException.class) // public void testInvalidFormat() throws Exception; // @Test // public void testIterator() throws Exception; // @Test // public void testLineFeedEndings() throws IOException; // @Test // public void testMappedButNotSetAsOutlook2007ContactExport() throws Exception; // @Test // // TODO this may lead to strange behavior, throw an exception if iterator() has already been called? // public void testMultipleIterators() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testNewCSVParserNullReaderFormat() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testNewCSVParserReaderNullFormat() throws Exception; // @Test // public void testNoHeaderMap() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testParseFileNullFormat() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testParseNullFileFormat() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testParseNullStringFormat() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testParseNullUrlCharsetFormat() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testParserUrlNullCharsetFormat() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testParseStringNullFormat() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testParseUrlCharsetNullFormat() throws Exception; // @Test // public void testProvidedHeader() throws Exception; // @Test // public void testProvidedHeaderAuto() throws Exception; // @Test // public void testRoundtrip() throws Exception; // @Test // public void testSkipAutoHeader() throws Exception; // @Test // public void testSkipHeaderOverrideDuplicateHeaders() throws Exception; // @Test // public void testSkipSetAltHeaders() throws Exception; // @Test // public void testSkipSetHeader() throws Exception; // @Test // @Ignore // public void testStartWithEmptyLinesThenHeaders() throws Exception; // @Test // public void testTrailingDelimiter() throws Exception; // @Test // public void testTrim() throws Exception; // @Test // public void testIteratorSequenceBreaking() throws IOException; // private void validateLineNumbers(final String lineSeparator) throws IOException; // private void validateRecordNumbers(final String lineSeparator) throws IOException; // private void validateRecordPosition(final String lineSeparator) throws IOException; // } // You are a professional Java test case writer, please create a test case named `testGetOneLineOneParser` for the `CSVParser` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests reusing a parser to process new string records one at a time as they are being discovered. See [CSV-110]. * * @throws IOException */
src/test/java/org/apache/commons/csv/CSVParserTest.java
package org.apache.commons.csv; import static org.apache.commons.csv.Token.Type.TOKEN; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.TreeMap;
@SuppressWarnings("resource") public static CSVParser parse(final File file, final Charset charset, final CSVFormat format) throws IOException; @SuppressWarnings("resource") public static CSVParser parse(final InputStream inputStream, final Charset charset, final CSVFormat format) throws IOException; public static CSVParser parse(final Path path, final Charset charset, final CSVFormat format) throws IOException; public static CSVParser parse(final Reader reader, final CSVFormat format) throws IOException; public static CSVParser parse(final String string, final CSVFormat format) throws IOException; public static CSVParser parse(final URL url, final Charset charset, final CSVFormat format) throws IOException; public CSVParser(final Reader reader, final CSVFormat format) throws IOException; @SuppressWarnings("resource") public CSVParser(final Reader reader, final CSVFormat format, final long characterOffset, final long recordNumber) throws IOException; private void addRecordValue(final boolean lastRecord); @Override public void close() throws IOException; public long getCurrentLineNumber(); public String getFirstEndOfLine(); public Map<String, Integer> getHeaderMap(); public long getRecordNumber(); public List<CSVRecord> getRecords() throws IOException; private Map<String, Integer> initializeHeader() throws IOException; public boolean isClosed(); @Override public Iterator<CSVRecord> iterator(); CSVRecord nextRecord() throws IOException; private CSVRecord getNextRecord(); @Override public boolean hasNext(); @Override public CSVRecord next(); @Override public void remove();
545
testGetOneLineOneParser
```java + " \"foo\n,,\n\"\",,\n\"\"\",d,e\n"; private static final String CSV_INPUT_1 = "a,b,c,d"; private static final String CSV_INPUT_2 = "a,b,1 2"; private static final String[][] RESULT = { { "a", "b", "c", "d" }, { "a", "b", "1 2" }, { "foo baar", "b", "" }, { "foo\n,,\n\",,\n\"", "d", "e" } }; private BOMInputStream createBOMInputStream(final String resource) throws IOException; @Test public void testBackslashEscaping() throws IOException; @Test public void testBackslashEscaping2() throws IOException; @Test @Ignore public void testBackslashEscapingOld() throws IOException; @Test @Ignore("CSV-107") public void testBOM() throws IOException; @Test public void testBOMInputStream_ParserWithReader(); @Test public void testBOMInputStream_parseWithReader(); @Test public void testBOMInputStream_ParserWithInputStream(); @Test public void testCarriageReturnEndings() throws IOException; @Test public void testCarriageReturnLineFeedEndings() throws IOException; @Test public void testFirstEndOfLineCrLf() throws IOException; @Test public void testFirstEndOfLineLf() throws IOException; @Test public void testFirstEndOfLineCr() throws IOException; @Test(expected = NoSuchElementException.class) public void testClose() throws Exception; @Test public void testCSV57() throws Exception; @Test public void testDefaultFormat() throws IOException; @Test(expected = IllegalArgumentException.class) public void testDuplicateHeaders() throws Exception; @Test public void testEmptyFile() throws Exception; @Test public void testEmptyLineBehaviourCSV() throws Exception; @Test public void testEmptyLineBehaviourExcel() throws Exception; @Test public void testEndOfFileBehaviorCSV() throws Exception; @Test public void testEndOfFileBehaviourExcel() throws Exception; @Test public void testExcelFormat1() throws IOException; @Test public void testExcelFormat2() throws Exception; @Test public void testExcelHeaderCountLessThanData() throws Exception; @Test public void testForEach() throws Exception; @Test public void testGetHeaderMap() throws Exception; @Test public void testGetLine() throws IOException; @Test public void testGetLineNumberWithCR() throws Exception; @Test public void testGetLineNumberWithCRLF() throws Exception; @Test public void testGetLineNumberWithLF() throws Exception; @Test public void testGetOneLine() throws IOException; @Test public void testGetOneLineOneParser() throws IOException; @Test public void testGetRecordNumberWithCR() throws Exception; @Test public void testGetRecordNumberWithCRLF() throws Exception; @Test public void testGetRecordNumberWithLF() throws Exception; @Test public void testGetRecordPositionWithCRLF() throws Exception; @Test public void testGetRecordPositionWithLF() throws Exception; @Test public void testGetRecords() throws IOException; @Test public void testGetRecordWithMultiLineValues() throws Exception; @Test public void testHeader() throws Exception; @Test public void testHeaderComment() throws Exception; @Test public void testHeaderMissing() throws Exception; @Test public void testHeaderMissingWithNull() throws Exception; @Test public void testHeadersMissing() throws Exception; @Test(expected = IllegalArgumentException.class) public void testHeadersMissingException() throws Exception; @Test public void testIgnoreCaseHeaderMapping() throws Exception; @Test public void testIgnoreEmptyLines() throws IOException; @Test(expected = IllegalArgumentException.class) public void testInvalidFormat() throws Exception; @Test public void testIterator() throws Exception; @Test public void testLineFeedEndings() throws IOException; @Test public void testMappedButNotSetAsOutlook2007ContactExport() throws Exception; @Test // TODO this may lead to strange behavior, throw an exception if iterator() has already been called? public void testMultipleIterators() throws Exception; @Test(expected = IllegalArgumentException.class) public void testNewCSVParserNullReaderFormat() throws Exception; @Test(expected = IllegalArgumentException.class) public void testNewCSVParserReaderNullFormat() throws Exception; @Test public void testNoHeaderMap() throws Exception; @Test(expected = IllegalArgumentException.class) public void testParseFileNullFormat() throws Exception; @Test(expected = IllegalArgumentException.class) public void testParseNullFileFormat() throws Exception; @Test(expected = IllegalArgumentException.class) public void testParseNullStringFormat() throws Exception; @Test(expected = IllegalArgumentException.class) public void testParseNullUrlCharsetFormat() throws Exception; @Test(expected = IllegalArgumentException.class) public void testParserUrlNullCharsetFormat() throws Exception; @Test(expected = IllegalArgumentException.class) public void testParseStringNullFormat() throws Exception; @Test(expected = IllegalArgumentException.class) public void testParseUrlCharsetNullFormat() throws Exception; @Test public void testProvidedHeader() throws Exception; @Test public void testProvidedHeaderAuto() throws Exception; @Test public void testRoundtrip() throws Exception; @Test public void testSkipAutoHeader() throws Exception; @Test public void testSkipHeaderOverrideDuplicateHeaders() throws Exception; @Test public void testSkipSetAltHeaders() throws Exception; @Test public void testSkipSetHeader() throws Exception; @Test @Ignore public void testStartWithEmptyLinesThenHeaders() throws Exception; @Test public void testTrailingDelimiter() throws Exception; @Test public void testTrim() throws Exception; @Test public void testIteratorSequenceBreaking() throws IOException; private void validateLineNumbers(final String lineSeparator) throws IOException; private void validateRecordNumbers(final String lineSeparator) throws IOException; private void validateRecordPosition(final String lineSeparator) throws IOException; } ``` You are a professional Java test case writer, please create a test case named `testGetOneLineOneParser` for the `CSVParser` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests reusing a parser to process new string records one at a time as they are being discovered. See [CSV-110]. * * @throws IOException */
531
// + " \"foo\n,,\n\"\",,\n\"\"\",d,e\n"; // private static final String CSV_INPUT_1 = "a,b,c,d"; // private static final String CSV_INPUT_2 = "a,b,1 2"; // private static final String[][] RESULT = { { "a", "b", "c", "d" }, { "a", "b", "1 2" }, { "foo baar", "b", "" }, // { "foo\n,,\n\",,\n\"", "d", "e" } }; // // private BOMInputStream createBOMInputStream(final String resource) throws IOException; // @Test // public void testBackslashEscaping() throws IOException; // @Test // public void testBackslashEscaping2() throws IOException; // @Test // @Ignore // public void testBackslashEscapingOld() throws IOException; // @Test // @Ignore("CSV-107") // public void testBOM() throws IOException; // @Test // public void testBOMInputStream_ParserWithReader(); // @Test // public void testBOMInputStream_parseWithReader(); // @Test // public void testBOMInputStream_ParserWithInputStream(); // @Test // public void testCarriageReturnEndings() throws IOException; // @Test // public void testCarriageReturnLineFeedEndings() throws IOException; // @Test // public void testFirstEndOfLineCrLf() throws IOException; // @Test // public void testFirstEndOfLineLf() throws IOException; // @Test // public void testFirstEndOfLineCr() throws IOException; // @Test(expected = NoSuchElementException.class) // public void testClose() throws Exception; // @Test // public void testCSV57() throws Exception; // @Test // public void testDefaultFormat() throws IOException; // @Test(expected = IllegalArgumentException.class) // public void testDuplicateHeaders() throws Exception; // @Test // public void testEmptyFile() throws Exception; // @Test // public void testEmptyLineBehaviourCSV() throws Exception; // @Test // public void testEmptyLineBehaviourExcel() throws Exception; // @Test // public void testEndOfFileBehaviorCSV() throws Exception; // @Test // public void testEndOfFileBehaviourExcel() throws Exception; // @Test // public void testExcelFormat1() throws IOException; // @Test // public void testExcelFormat2() throws Exception; // @Test // public void testExcelHeaderCountLessThanData() throws Exception; // @Test // public void testForEach() throws Exception; // @Test // public void testGetHeaderMap() throws Exception; // @Test // public void testGetLine() throws IOException; // @Test // public void testGetLineNumberWithCR() throws Exception; // @Test // public void testGetLineNumberWithCRLF() throws Exception; // @Test // public void testGetLineNumberWithLF() throws Exception; // @Test // public void testGetOneLine() throws IOException; // @Test // public void testGetOneLineOneParser() throws IOException; // @Test // public void testGetRecordNumberWithCR() throws Exception; // @Test // public void testGetRecordNumberWithCRLF() throws Exception; // @Test // public void testGetRecordNumberWithLF() throws Exception; // @Test // public void testGetRecordPositionWithCRLF() throws Exception; // @Test // public void testGetRecordPositionWithLF() throws Exception; // @Test // public void testGetRecords() throws IOException; // @Test // public void testGetRecordWithMultiLineValues() throws Exception; // @Test // public void testHeader() throws Exception; // @Test // public void testHeaderComment() throws Exception; // @Test // public void testHeaderMissing() throws Exception; // @Test // public void testHeaderMissingWithNull() throws Exception; // @Test // public void testHeadersMissing() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testHeadersMissingException() throws Exception; // @Test // public void testIgnoreCaseHeaderMapping() throws Exception; // @Test // public void testIgnoreEmptyLines() throws IOException; // @Test(expected = IllegalArgumentException.class) // public void testInvalidFormat() throws Exception; // @Test // public void testIterator() throws Exception; // @Test // public void testLineFeedEndings() throws IOException; // @Test // public void testMappedButNotSetAsOutlook2007ContactExport() throws Exception; // @Test // // TODO this may lead to strange behavior, throw an exception if iterator() has already been called? // public void testMultipleIterators() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testNewCSVParserNullReaderFormat() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testNewCSVParserReaderNullFormat() throws Exception; // @Test // public void testNoHeaderMap() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testParseFileNullFormat() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testParseNullFileFormat() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testParseNullStringFormat() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testParseNullUrlCharsetFormat() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testParserUrlNullCharsetFormat() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testParseStringNullFormat() throws Exception; // @Test(expected = IllegalArgumentException.class) // public void testParseUrlCharsetNullFormat() throws Exception; // @Test // public void testProvidedHeader() throws Exception; // @Test // public void testProvidedHeaderAuto() throws Exception; // @Test // public void testRoundtrip() throws Exception; // @Test // public void testSkipAutoHeader() throws Exception; // @Test // public void testSkipHeaderOverrideDuplicateHeaders() throws Exception; // @Test // public void testSkipSetAltHeaders() throws Exception; // @Test // public void testSkipSetHeader() throws Exception; // @Test // @Ignore // public void testStartWithEmptyLinesThenHeaders() throws Exception; // @Test // public void testTrailingDelimiter() throws Exception; // @Test // public void testTrim() throws Exception; // @Test // public void testIteratorSequenceBreaking() throws IOException; // private void validateLineNumbers(final String lineSeparator) throws IOException; // private void validateRecordNumbers(final String lineSeparator) throws IOException; // private void validateRecordPosition(final String lineSeparator) throws IOException; // } // You are a professional Java test case writer, please create a test case named `testGetOneLineOneParser` for the `CSVParser` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests reusing a parser to process new string records one at a time as they are being discovered. See [CSV-110]. * * @throws IOException */ @Test public void testGetOneLineOneParser() throws IOException {
/** * Tests reusing a parser to process new string records one at a time as they are being discovered. See [CSV-110]. * * @throws IOException */
16
org.apache.commons.csv.CSVParser
src/test/java
```java + " \"foo\n,,\n\"\",,\n\"\"\",d,e\n"; private static final String CSV_INPUT_1 = "a,b,c,d"; private static final String CSV_INPUT_2 = "a,b,1 2"; private static final String[][] RESULT = { { "a", "b", "c", "d" }, { "a", "b", "1 2" }, { "foo baar", "b", "" }, { "foo\n,,\n\",,\n\"", "d", "e" } }; private BOMInputStream createBOMInputStream(final String resource) throws IOException; @Test public void testBackslashEscaping() throws IOException; @Test public void testBackslashEscaping2() throws IOException; @Test @Ignore public void testBackslashEscapingOld() throws IOException; @Test @Ignore("CSV-107") public void testBOM() throws IOException; @Test public void testBOMInputStream_ParserWithReader(); @Test public void testBOMInputStream_parseWithReader(); @Test public void testBOMInputStream_ParserWithInputStream(); @Test public void testCarriageReturnEndings() throws IOException; @Test public void testCarriageReturnLineFeedEndings() throws IOException; @Test public void testFirstEndOfLineCrLf() throws IOException; @Test public void testFirstEndOfLineLf() throws IOException; @Test public void testFirstEndOfLineCr() throws IOException; @Test(expected = NoSuchElementException.class) public void testClose() throws Exception; @Test public void testCSV57() throws Exception; @Test public void testDefaultFormat() throws IOException; @Test(expected = IllegalArgumentException.class) public void testDuplicateHeaders() throws Exception; @Test public void testEmptyFile() throws Exception; @Test public void testEmptyLineBehaviourCSV() throws Exception; @Test public void testEmptyLineBehaviourExcel() throws Exception; @Test public void testEndOfFileBehaviorCSV() throws Exception; @Test public void testEndOfFileBehaviourExcel() throws Exception; @Test public void testExcelFormat1() throws IOException; @Test public void testExcelFormat2() throws Exception; @Test public void testExcelHeaderCountLessThanData() throws Exception; @Test public void testForEach() throws Exception; @Test public void testGetHeaderMap() throws Exception; @Test public void testGetLine() throws IOException; @Test public void testGetLineNumberWithCR() throws Exception; @Test public void testGetLineNumberWithCRLF() throws Exception; @Test public void testGetLineNumberWithLF() throws Exception; @Test public void testGetOneLine() throws IOException; @Test public void testGetOneLineOneParser() throws IOException; @Test public void testGetRecordNumberWithCR() throws Exception; @Test public void testGetRecordNumberWithCRLF() throws Exception; @Test public void testGetRecordNumberWithLF() throws Exception; @Test public void testGetRecordPositionWithCRLF() throws Exception; @Test public void testGetRecordPositionWithLF() throws Exception; @Test public void testGetRecords() throws IOException; @Test public void testGetRecordWithMultiLineValues() throws Exception; @Test public void testHeader() throws Exception; @Test public void testHeaderComment() throws Exception; @Test public void testHeaderMissing() throws Exception; @Test public void testHeaderMissingWithNull() throws Exception; @Test public void testHeadersMissing() throws Exception; @Test(expected = IllegalArgumentException.class) public void testHeadersMissingException() throws Exception; @Test public void testIgnoreCaseHeaderMapping() throws Exception; @Test public void testIgnoreEmptyLines() throws IOException; @Test(expected = IllegalArgumentException.class) public void testInvalidFormat() throws Exception; @Test public void testIterator() throws Exception; @Test public void testLineFeedEndings() throws IOException; @Test public void testMappedButNotSetAsOutlook2007ContactExport() throws Exception; @Test // TODO this may lead to strange behavior, throw an exception if iterator() has already been called? public void testMultipleIterators() throws Exception; @Test(expected = IllegalArgumentException.class) public void testNewCSVParserNullReaderFormat() throws Exception; @Test(expected = IllegalArgumentException.class) public void testNewCSVParserReaderNullFormat() throws Exception; @Test public void testNoHeaderMap() throws Exception; @Test(expected = IllegalArgumentException.class) public void testParseFileNullFormat() throws Exception; @Test(expected = IllegalArgumentException.class) public void testParseNullFileFormat() throws Exception; @Test(expected = IllegalArgumentException.class) public void testParseNullStringFormat() throws Exception; @Test(expected = IllegalArgumentException.class) public void testParseNullUrlCharsetFormat() throws Exception; @Test(expected = IllegalArgumentException.class) public void testParserUrlNullCharsetFormat() throws Exception; @Test(expected = IllegalArgumentException.class) public void testParseStringNullFormat() throws Exception; @Test(expected = IllegalArgumentException.class) public void testParseUrlCharsetNullFormat() throws Exception; @Test public void testProvidedHeader() throws Exception; @Test public void testProvidedHeaderAuto() throws Exception; @Test public void testRoundtrip() throws Exception; @Test public void testSkipAutoHeader() throws Exception; @Test public void testSkipHeaderOverrideDuplicateHeaders() throws Exception; @Test public void testSkipSetAltHeaders() throws Exception; @Test public void testSkipSetHeader() throws Exception; @Test @Ignore public void testStartWithEmptyLinesThenHeaders() throws Exception; @Test public void testTrailingDelimiter() throws Exception; @Test public void testTrim() throws Exception; @Test public void testIteratorSequenceBreaking() throws IOException; private void validateLineNumbers(final String lineSeparator) throws IOException; private void validateRecordNumbers(final String lineSeparator) throws IOException; private void validateRecordPosition(final String lineSeparator) throws IOException; } ``` You are a professional Java test case writer, please create a test case named `testGetOneLineOneParser` for the `CSVParser` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests reusing a parser to process new string records one at a time as they are being discovered. See [CSV-110]. * * @throws IOException */ @Test public void testGetOneLineOneParser() throws IOException { ```
public final class CSVParser implements Iterable<CSVRecord>, Closeable
package org.apache.commons.csv; import static org.apache.commons.csv.Constants.CR; import static org.apache.commons.csv.Constants.CRLF; import static org.apache.commons.csv.Constants.LF; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.PipedReader; import java.io.PipedWriter; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import org.apache.commons.io.input.BOMInputStream; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test;
private BOMInputStream createBOMInputStream(final String resource) throws IOException; @Test public void testBackslashEscaping() throws IOException; @Test public void testBackslashEscaping2() throws IOException; @Test @Ignore public void testBackslashEscapingOld() throws IOException; @Test @Ignore("CSV-107") public void testBOM() throws IOException; @Test public void testBOMInputStream_ParserWithReader(); @Test public void testBOMInputStream_parseWithReader(); @Test public void testBOMInputStream_ParserWithInputStream(); @Test public void testCarriageReturnEndings() throws IOException; @Test public void testCarriageReturnLineFeedEndings() throws IOException; @Test public void testFirstEndOfLineCrLf() throws IOException; @Test public void testFirstEndOfLineLf() throws IOException; @Test public void testFirstEndOfLineCr() throws IOException; @Test(expected = NoSuchElementException.class) public void testClose() throws Exception; @Test public void testCSV57() throws Exception; @Test public void testDefaultFormat() throws IOException; @Test(expected = IllegalArgumentException.class) public void testDuplicateHeaders() throws Exception; @Test public void testEmptyFile() throws Exception; @Test public void testEmptyLineBehaviourCSV() throws Exception; @Test public void testEmptyLineBehaviourExcel() throws Exception; @Test public void testEndOfFileBehaviorCSV() throws Exception; @Test public void testEndOfFileBehaviourExcel() throws Exception; @Test public void testExcelFormat1() throws IOException; @Test public void testExcelFormat2() throws Exception; @Test public void testExcelHeaderCountLessThanData() throws Exception; @Test public void testForEach() throws Exception; @Test public void testGetHeaderMap() throws Exception; @Test public void testGetLine() throws IOException; @Test public void testGetLineNumberWithCR() throws Exception; @Test public void testGetLineNumberWithCRLF() throws Exception; @Test public void testGetLineNumberWithLF() throws Exception; @Test public void testGetOneLine() throws IOException; @Test public void testGetOneLineOneParser() throws IOException; @Test public void testGetRecordNumberWithCR() throws Exception; @Test public void testGetRecordNumberWithCRLF() throws Exception; @Test public void testGetRecordNumberWithLF() throws Exception; @Test public void testGetRecordPositionWithCRLF() throws Exception; @Test public void testGetRecordPositionWithLF() throws Exception; @Test public void testGetRecords() throws IOException; @Test public void testGetRecordWithMultiLineValues() throws Exception; @Test public void testHeader() throws Exception; @Test public void testHeaderComment() throws Exception; @Test public void testHeaderMissing() throws Exception; @Test public void testHeaderMissingWithNull() throws Exception; @Test public void testHeadersMissing() throws Exception; @Test(expected = IllegalArgumentException.class) public void testHeadersMissingException() throws Exception; @Test public void testIgnoreCaseHeaderMapping() throws Exception; @Test public void testIgnoreEmptyLines() throws IOException; @Test(expected = IllegalArgumentException.class) public void testInvalidFormat() throws Exception; @Test public void testIterator() throws Exception; @Test public void testLineFeedEndings() throws IOException; @Test public void testMappedButNotSetAsOutlook2007ContactExport() throws Exception; @Test // TODO this may lead to strange behavior, throw an exception if iterator() has already been called? public void testMultipleIterators() throws Exception; @Test(expected = IllegalArgumentException.class) public void testNewCSVParserNullReaderFormat() throws Exception; @Test(expected = IllegalArgumentException.class) public void testNewCSVParserReaderNullFormat() throws Exception; @Test public void testNoHeaderMap() throws Exception; @Test(expected = IllegalArgumentException.class) public void testParseFileNullFormat() throws Exception; @Test(expected = IllegalArgumentException.class) public void testParseNullFileFormat() throws Exception; @Test(expected = IllegalArgumentException.class) public void testParseNullStringFormat() throws Exception; @Test(expected = IllegalArgumentException.class) public void testParseNullUrlCharsetFormat() throws Exception; @Test(expected = IllegalArgumentException.class) public void testParserUrlNullCharsetFormat() throws Exception; @Test(expected = IllegalArgumentException.class) public void testParseStringNullFormat() throws Exception; @Test(expected = IllegalArgumentException.class) public void testParseUrlCharsetNullFormat() throws Exception; @Test public void testProvidedHeader() throws Exception; @Test public void testProvidedHeaderAuto() throws Exception; @Test public void testRoundtrip() throws Exception; @Test public void testSkipAutoHeader() throws Exception; @Test public void testSkipHeaderOverrideDuplicateHeaders() throws Exception; @Test public void testSkipSetAltHeaders() throws Exception; @Test public void testSkipSetHeader() throws Exception; @Test @Ignore public void testStartWithEmptyLinesThenHeaders() throws Exception; @Test public void testTrailingDelimiter() throws Exception; @Test public void testTrim() throws Exception; @Test public void testIteratorSequenceBreaking() throws IOException; private void validateLineNumbers(final String lineSeparator) throws IOException; private void validateRecordNumbers(final String lineSeparator) throws IOException; private void validateRecordPosition(final String lineSeparator) throws IOException;
a18fb651934d5375cc19cb9f1fe435ba8ff1eef8092e0d7bbc17478882482d9a
[ "org.apache.commons.csv.CSVParserTest::testGetOneLineOneParser" ]
private final CSVFormat format; private final Map<String, Integer> headerMap; private final Lexer lexer; private final CSVRecordIterator csvRecordIterator; private final List<String> recordList = new ArrayList<>(); private long recordNumber; private final long characterOffset; private final Token reusableToken = new Token();
@Test public void testGetOneLineOneParser() throws IOException
private static final Charset UTF_8 = StandardCharsets.UTF_8; private static final String UTF_8_NAME = UTF_8.name(); private static final String CSV_INPUT = "a,b,c,d\n" + " a , b , 1 2 \n" + "\"foo baar\", b,\n" // + " \"foo\n,,\n\"\",,\n\\\"\",d,e\n"; + " \"foo\n,,\n\"\",,\n\"\"\",d,e\n"; private static final String CSV_INPUT_1 = "a,b,c,d"; private static final String CSV_INPUT_2 = "a,b,1 2"; private static final String[][] RESULT = { { "a", "b", "c", "d" }, { "a", "b", "1 2" }, { "foo baar", "b", "" }, { "foo\n,,\n\",,\n\"", "d", "e" } };
Csv
/* * 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.csv; import static org.apache.commons.csv.Constants.CR; import static org.apache.commons.csv.Constants.CRLF; import static org.apache.commons.csv.Constants.LF; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.PipedReader; import java.io.PipedWriter; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import org.apache.commons.io.input.BOMInputStream; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; /** * CSVParserTest * * The test are organized in three different sections: The 'setter/getter' section, the lexer section and finally the * parser section. In case a test fails, you should follow a top-down approach for fixing a potential bug (its likely * that the parser itself fails if the lexer has problems...). */ public class CSVParserTest { private static final Charset UTF_8 = StandardCharsets.UTF_8; private static final String UTF_8_NAME = UTF_8.name(); private static final String CSV_INPUT = "a,b,c,d\n" + " a , b , 1 2 \n" + "\"foo baar\", b,\n" // + " \"foo\n,,\n\"\",,\n\\\"\",d,e\n"; + " \"foo\n,,\n\"\",,\n\"\"\",d,e\n"; // changed to use standard CSV escaping private static final String CSV_INPUT_1 = "a,b,c,d"; private static final String CSV_INPUT_2 = "a,b,1 2"; private static final String[][] RESULT = { { "a", "b", "c", "d" }, { "a", "b", "1 2" }, { "foo baar", "b", "" }, { "foo\n,,\n\",,\n\"", "d", "e" } }; private BOMInputStream createBOMInputStream(final String resource) throws IOException { final URL url = ClassLoader.getSystemClassLoader().getResource(resource); return new BOMInputStream(url.openStream()); } @Test public void testBackslashEscaping() throws IOException { // To avoid confusion over the need for escaping chars in java code, // We will test with a forward slash as the escape char, and a single // quote as the encapsulator. final String code = "one,two,three\n" // 0 + "'',''\n" // 1) empty encapsulators + "/',/'\n" // 2) single encapsulators + "'/'','/''\n" // 3) single encapsulators encapsulated via escape + "'''',''''\n" // 4) single encapsulators encapsulated via doubling + "/,,/,\n" // 5) separator escaped + "//,//\n" // 6) escape escaped + "'//','//'\n" // 7) escape escaped in encapsulation + " 8 , \"quoted \"\" /\" // string\" \n" // don't eat spaces + "9, /\n \n" // escaped newline + ""; final String[][] res = { { "one", "two", "three" }, // 0 { "", "" }, // 1 { "'", "'" }, // 2 { "'", "'" }, // 3 { "'", "'" }, // 4 { ",", "," }, // 5 { "/", "/" }, // 6 { "/", "/" }, // 7 { " 8 ", " \"quoted \"\" /\" / string\" " }, { "9", " \n " }, }; final CSVFormat format = CSVFormat.newFormat(',').withQuote('\'').withRecordSeparator(CRLF).withEscape('/') .withIgnoreEmptyLines(); try (final CSVParser parser = CSVParser.parse(code, format)) { final List<CSVRecord> records = parser.getRecords(); assertTrue(records.size() > 0); Utils.compare("Records do not match expected result", res, records); } } @Test public void testBackslashEscaping2() throws IOException { // To avoid confusion over the need for escaping chars in java code, // We will test with a forward slash as the escape char, and a single // quote as the encapsulator. final String code = "" + " , , \n" // 1) + " \t , , \n" // 2) + " // , /, , /,\n" // 3) + ""; final String[][] res = { { " ", " ", " " }, // 1 { " \t ", " ", " " }, // 2 { " / ", " , ", " ," }, // 3 }; final CSVFormat format = CSVFormat.newFormat(',').withRecordSeparator(CRLF).withEscape('/') .withIgnoreEmptyLines(); try (final CSVParser parser = CSVParser.parse(code, format)) { final List<CSVRecord> records = parser.getRecords(); assertTrue(records.size() > 0); Utils.compare("", res, records); } } @Test @Ignore public void testBackslashEscapingOld() throws IOException { final String code = "one,two,three\n" + "on\\\"e,two\n" + "on\"e,two\n" + "one,\"tw\\\"o\"\n" + "one,\"t\\,wo\"\n" + "one,two,\"th,ree\"\n" + "\"a\\\\\"\n" + "a\\,b\n" + "\"a\\\\,b\""; final String[][] res = { { "one", "two", "three" }, { "on\\\"e", "two" }, { "on\"e", "two" }, { "one", "tw\"o" }, { "one", "t\\,wo" }, // backslash in quotes only escapes a delimiter (",") { "one", "two", "th,ree" }, { "a\\\\" }, // backslash in quotes only escapes a delimiter (",") { "a\\", "b" }, // a backslash must be returnd { "a\\\\,b" } // backslash in quotes only escapes a delimiter (",") }; try (final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT)) { final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } } @Test @Ignore("CSV-107") public void testBOM() throws IOException { final URL url = ClassLoader.getSystemClassLoader().getResource("CSVFileParser/bom.csv"); try (final CSVParser parser = CSVParser.parse(url, Charset.forName(UTF_8_NAME), CSVFormat.EXCEL.withHeader())) { for (final CSVRecord record : parser) { final String string = record.get("Date"); Assert.assertNotNull(string); // System.out.println("date: " + record.get("Date")); } } } @Test public void testBOMInputStream_ParserWithReader() {} // Defects4J: flaky method // @Test // public void testBOMInputStream_ParserWithReader() throws IOException { // try (final Reader reader = new InputStreamReader(createBOMInputStream("CSVFileParser/bom.csv"), UTF_8_NAME); // final CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader())) { // for (final CSVRecord record : parser) { // final String string = record.get("Date"); // Assert.assertNotNull(string); // // System.out.println("date: " + record.get("Date")); // } // } // } @Test public void testBOMInputStream_parseWithReader() {} // Defects4J: flaky method // @Test // public void testBOMInputStream_parseWithReader() throws IOException { // try (final Reader reader = new InputStreamReader(createBOMInputStream("CSVFileParser/bom.csv"), UTF_8_NAME); // final CSVParser parser = CSVParser.parse(reader, CSVFormat.EXCEL.withHeader())) { // for (final CSVRecord record : parser) { // final String string = record.get("Date"); // Assert.assertNotNull(string); // // System.out.println("date: " + record.get("Date")); // } // } // } @Test public void testBOMInputStream_ParserWithInputStream() {} // Defects4J: flaky method // @Test // public void testBOMInputStream_ParserWithInputStream() throws IOException { // try (final BOMInputStream inputStream = createBOMInputStream("CSVFileParser/bom.csv"); // final CSVParser parser = CSVParser.parse(inputStream, UTF_8, CSVFormat.EXCEL.withHeader())) { // for (final CSVRecord record : parser) { // final String string = record.get("Date"); // Assert.assertNotNull(string); // // System.out.println("date: " + record.get("Date")); // } // } // } @Test public void testCarriageReturnEndings() throws IOException { final String code = "foo\rbaar,\rhello,world\r,kanu"; try (final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT)) { final List<CSVRecord> records = parser.getRecords(); assertEquals(4, records.size()); } } @Test public void testCarriageReturnLineFeedEndings() throws IOException { final String code = "foo\r\nbaar,\r\nhello,world\r\n,kanu"; try (final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT)) { final List<CSVRecord> records = parser.getRecords(); assertEquals(4, records.size()); } } @Test public void testFirstEndOfLineCrLf() throws IOException { final String data = "foo\r\nbaar,\r\nhello,world\r\n,kanu"; try (final CSVParser parser = CSVParser.parse(data, CSVFormat.DEFAULT)) { final List<CSVRecord> records = parser.getRecords(); assertEquals(4, records.size()); assertEquals("\r\n", parser.getFirstEndOfLine()); } } @Test public void testFirstEndOfLineLf() throws IOException { final String data = "foo\nbaar,\nhello,world\n,kanu"; try (final CSVParser parser = CSVParser.parse(data, CSVFormat.DEFAULT)) { final List<CSVRecord> records = parser.getRecords(); assertEquals(4, records.size()); assertEquals("\n", parser.getFirstEndOfLine()); } } @Test public void testFirstEndOfLineCr() throws IOException { final String data = "foo\rbaar,\rhello,world\r,kanu"; try (final CSVParser parser = CSVParser.parse(data, CSVFormat.DEFAULT)) { final List<CSVRecord> records = parser.getRecords(); assertEquals(4, records.size()); assertEquals("\r", parser.getFirstEndOfLine()); } } @Test(expected = NoSuchElementException.class) public void testClose() throws Exception { final Reader in = new StringReader("# comment\na,b,c\n1,2,3\nx,y,z"); final Iterator<CSVRecord> records; try (final CSVParser parser = CSVFormat.DEFAULT.withCommentMarker('#').withHeader().parse(in)) { records = parser.iterator(); assertTrue(records.hasNext()); } assertFalse(records.hasNext()); records.next(); } @Test public void testCSV57() throws Exception { try (final CSVParser parser = CSVParser.parse("", CSVFormat.DEFAULT)) { final List<CSVRecord> list = parser.getRecords(); assertNotNull(list); assertEquals(0, list.size()); } } @Test public void testDefaultFormat() throws IOException { final String code = "" + "a,b#\n" // 1) + "\"\n\",\" \",#\n" // 2) + "#,\"\"\n" // 3) + "# Final comment\n"// 4) ; final String[][] res = { { "a", "b#" }, { "\n", " ", "#" }, { "#", "" }, { "# Final comment" } }; CSVFormat format = CSVFormat.DEFAULT; assertFalse(format.isCommentMarkerSet()); final String[][] res_comments = { { "a", "b#" }, { "\n", " ", "#" }, }; try (final CSVParser parser = CSVParser.parse(code, format)) { final List<CSVRecord> records = parser.getRecords(); assertTrue(records.size() > 0); Utils.compare("Failed to parse without comments", res, records); format = CSVFormat.DEFAULT.withCommentMarker('#'); } try (final CSVParser parser = CSVParser.parse(code, format)) { final List<CSVRecord> records = parser.getRecords(); Utils.compare("Failed to parse with comments", res_comments, records); } } @Test(expected = IllegalArgumentException.class) public void testDuplicateHeaders() throws Exception { CSVParser.parse("a,b,a\n1,2,3\nx,y,z", CSVFormat.DEFAULT.withHeader(new String[] {})); } @Test public void testEmptyFile() throws Exception { try (final CSVParser parser = CSVParser.parse("", CSVFormat.DEFAULT)) { assertNull(parser.nextRecord()); } } @Test public void testEmptyLineBehaviourCSV() throws Exception { final String[] codes = { "hello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", "hello,\"\"\n\n\n" }; final String[][] res = { { "hello", "" } // CSV format ignores empty lines }; for (final String code : codes) { try (final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT)) { final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } } } @Test public void testEmptyLineBehaviourExcel() throws Exception { final String[] codes = { "hello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", "hello,\"\"\n\n\n" }; final String[][] res = { { "hello", "" }, { "" }, // Excel format does not ignore empty lines { "" } }; for (final String code : codes) { try (final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL)) { final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } } } @Test public void testEndOfFileBehaviorCSV() throws Exception { final String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; final String[][] res = { { "hello", "" }, // CSV format ignores empty lines { "world", "" } }; for (final String code : codes) { try (final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT)) { final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } } } @Test public void testEndOfFileBehaviourExcel() throws Exception { final String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; final String[][] res = { { "hello", "" }, { "" }, // Excel format does not ignore empty lines { "world", "" } }; for (final String code : codes) { try (final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL)) { final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } } } @Test public void testExcelFormat1() throws IOException { final String code = "value1,value2,value3,value4\r\na,b,c,d\r\n x,,," + "\r\n\r\n\"\"\"hello\"\"\",\" \"\"world\"\"\",\"abc\ndef\",\r\n"; final String[][] res = { { "value1", "value2", "value3", "value4" }, { "a", "b", "c", "d" }, { " x", "", "", "" }, { "" }, { "\"hello\"", " \"world\"", "abc\ndef", "" } }; try (final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL)) { final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } } @Test public void testExcelFormat2() throws Exception { final String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n"; final String[][] res = { { "foo", "baar" }, { "" }, { "hello", "" }, { "" }, { "world", "" } }; try (final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL)) { final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } } /** * Tests an exported Excel worksheet with a header row and rows that have more columns than the headers */ @Test public void testExcelHeaderCountLessThanData() throws Exception { final String code = "A,B,C,,\r\na,b,c,d,e\r\n"; try (final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL.withHeader())) { for (final CSVRecord record : parser.getRecords()) { Assert.assertEquals("a", record.get("A")); Assert.assertEquals("b", record.get("B")); Assert.assertEquals("c", record.get("C")); } } } @Test public void testForEach() throws Exception { final List<CSVRecord> records = new ArrayList<>(); try (final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z")) { for (final CSVRecord record : CSVFormat.DEFAULT.parse(in)) { records.add(record); } assertEquals(3, records.size()); assertArrayEquals(new String[] { "a", "b", "c" }, records.get(0).values()); assertArrayEquals(new String[] { "1", "2", "3" }, records.get(1).values()); assertArrayEquals(new String[] { "x", "y", "z" }, records.get(2).values()); } } @Test public void testGetHeaderMap() throws Exception { try (final CSVParser parser = CSVParser.parse("a,b,c\n1,2,3\nx,y,z", CSVFormat.DEFAULT.withHeader("A", "B", "C"))) { final Map<String, Integer> headerMap = parser.getHeaderMap(); final Iterator<String> columnNames = headerMap.keySet().iterator(); // Headers are iterated in column order. Assert.assertEquals("A", columnNames.next()); Assert.assertEquals("B", columnNames.next()); Assert.assertEquals("C", columnNames.next()); final Iterator<CSVRecord> records = parser.iterator(); // Parse to make sure getHeaderMap did not have a side-effect. for (int i = 0; i < 3; i++) { assertTrue(records.hasNext()); final CSVRecord record = records.next(); assertEquals(record.get(0), record.get("A")); assertEquals(record.get(1), record.get("B")); assertEquals(record.get(2), record.get("C")); } assertFalse(records.hasNext()); } } @Test public void testGetLine() throws IOException { try (final CSVParser parser = CSVParser.parse(CSV_INPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces())) { for (final String[] re : RESULT) { assertArrayEquals(re, parser.nextRecord().values()); } assertNull(parser.nextRecord()); } } @Test public void testGetLineNumberWithCR() throws Exception { this.validateLineNumbers(String.valueOf(CR)); } @Test public void testGetLineNumberWithCRLF() throws Exception { this.validateLineNumbers(CRLF); } @Test public void testGetLineNumberWithLF() throws Exception { this.validateLineNumbers(String.valueOf(LF)); } @Test public void testGetOneLine() throws IOException { try (final CSVParser parser = CSVParser.parse(CSV_INPUT_1, CSVFormat.DEFAULT)) { final CSVRecord record = parser.getRecords().get(0); assertArrayEquals(RESULT[0], record.values()); } } /** * Tests reusing a parser to process new string records one at a time as they are being discovered. See [CSV-110]. * * @throws IOException */ @Test public void testGetOneLineOneParser() throws IOException { final CSVFormat format = CSVFormat.DEFAULT; try (final PipedWriter writer = new PipedWriter(); final CSVParser parser = new CSVParser(new PipedReader(writer), format)) { writer.append(CSV_INPUT_1); writer.append(format.getRecordSeparator()); final CSVRecord record1 = parser.nextRecord(); assertArrayEquals(RESULT[0], record1.values()); writer.append(CSV_INPUT_2); writer.append(format.getRecordSeparator()); final CSVRecord record2 = parser.nextRecord(); assertArrayEquals(RESULT[1], record2.values()); } } @Test public void testGetRecordNumberWithCR() throws Exception { this.validateRecordNumbers(String.valueOf(CR)); } @Test public void testGetRecordNumberWithCRLF() throws Exception { this.validateRecordNumbers(CRLF); } @Test public void testGetRecordNumberWithLF() throws Exception { this.validateRecordNumbers(String.valueOf(LF)); } @Test public void testGetRecordPositionWithCRLF() throws Exception { this.validateRecordPosition(CRLF); } @Test public void testGetRecordPositionWithLF() throws Exception { this.validateRecordPosition(String.valueOf(LF)); } @Test public void testGetRecords() throws IOException { try (final CSVParser parser = CSVParser.parse(CSV_INPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces())) { final List<CSVRecord> records = parser.getRecords(); assertEquals(RESULT.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < RESULT.length; i++) { assertArrayEquals(RESULT[i], records.get(i).values()); } } } @Test public void testGetRecordWithMultiLineValues() throws Exception { try (final CSVParser parser = CSVParser.parse( "\"a\r\n1\",\"a\r\n2\"" + CRLF + "\"b\r\n1\",\"b\r\n2\"" + CRLF + "\"c\r\n1\",\"c\r\n2\"", CSVFormat.DEFAULT.withRecordSeparator(CRLF))) { CSVRecord record; assertEquals(0, parser.getRecordNumber()); assertEquals(0, parser.getCurrentLineNumber()); assertNotNull(record = parser.nextRecord()); assertEquals(3, parser.getCurrentLineNumber()); assertEquals(1, record.getRecordNumber()); assertEquals(1, parser.getRecordNumber()); assertNotNull(record = parser.nextRecord()); assertEquals(6, parser.getCurrentLineNumber()); assertEquals(2, record.getRecordNumber()); assertEquals(2, parser.getRecordNumber()); assertNotNull(record = parser.nextRecord()); assertEquals(8, parser.getCurrentLineNumber()); assertEquals(3, record.getRecordNumber()); assertEquals(3, parser.getRecordNumber()); assertNull(record = parser.nextRecord()); assertEquals(8, parser.getCurrentLineNumber()); assertEquals(3, parser.getRecordNumber()); } } @Test public void testHeader() throws Exception { final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); for (int i = 0; i < 2; i++) { assertTrue(records.hasNext()); final CSVRecord record = records.next(); assertEquals(record.get(0), record.get("a")); assertEquals(record.get(1), record.get("b")); assertEquals(record.get(2), record.get("c")); } assertFalse(records.hasNext()); } @Test public void testHeaderComment() throws Exception { final Reader in = new StringReader("# comment\na,b,c\n1,2,3\nx,y,z"); final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withCommentMarker('#').withHeader().parse(in).iterator(); for (int i = 0; i < 2; i++) { assertTrue(records.hasNext()); final CSVRecord record = records.next(); assertEquals(record.get(0), record.get("a")); assertEquals(record.get(1), record.get("b")); assertEquals(record.get(2), record.get("c")); } assertFalse(records.hasNext()); } @Test public void testHeaderMissing() throws Exception { final Reader in = new StringReader("a,,c\n1,2,3\nx,y,z"); final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); for (int i = 0; i < 2; i++) { assertTrue(records.hasNext()); final CSVRecord record = records.next(); assertEquals(record.get(0), record.get("a")); assertEquals(record.get(2), record.get("c")); } assertFalse(records.hasNext()); } @Test public void testHeaderMissingWithNull() throws Exception { final Reader in = new StringReader("a,,c,,d\n1,2,3,4\nx,y,z,zz"); CSVFormat.DEFAULT.withHeader().withNullString("").withAllowMissingColumnNames().parse(in).iterator(); } @Test public void testHeadersMissing() throws Exception { final Reader in = new StringReader("a,,c,,d\n1,2,3,4\nx,y,z,zz"); CSVFormat.DEFAULT.withHeader().withAllowMissingColumnNames().parse(in).iterator(); } @Test(expected = IllegalArgumentException.class) public void testHeadersMissingException() throws Exception { final Reader in = new StringReader("a,,c,,d\n1,2,3,4\nx,y,z,zz"); CSVFormat.DEFAULT.withHeader().parse(in).iterator(); } @Test public void testIgnoreCaseHeaderMapping() throws Exception { final Reader in = new StringReader("1,2,3"); final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader("One", "TWO", "three").withIgnoreHeaderCase() .parse(in).iterator(); final CSVRecord record = records.next(); assertEquals("1", record.get("one")); assertEquals("2", record.get("two")); assertEquals("3", record.get("THREE")); } @Test public void testIgnoreEmptyLines() throws IOException { final String code = "\nfoo,baar\n\r\n,\n\n,world\r\n\n"; // String code = "world\r\n\n"; // String code = "foo;baar\r\n\r\nhello;\r\n\r\nworld;\r\n"; try (final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT)) { final List<CSVRecord> records = parser.getRecords(); assertEquals(3, records.size()); } } @Test(expected = IllegalArgumentException.class) public void testInvalidFormat() throws Exception { final CSVFormat invalidFormat = CSVFormat.DEFAULT.withDelimiter(CR); try (final CSVParser parser = new CSVParser(null, invalidFormat)) { Assert.fail("This test should have thrown an exception."); } } @Test public void testIterator() throws Exception { final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); final Iterator<CSVRecord> iterator = CSVFormat.DEFAULT.parse(in).iterator(); assertTrue(iterator.hasNext()); try { iterator.remove(); fail("expected UnsupportedOperationException"); } catch (final UnsupportedOperationException expected) { // expected } assertArrayEquals(new String[] { "a", "b", "c" }, iterator.next().values()); assertArrayEquals(new String[] { "1", "2", "3" }, iterator.next().values()); assertTrue(iterator.hasNext()); assertTrue(iterator.hasNext()); assertTrue(iterator.hasNext()); assertArrayEquals(new String[] { "x", "y", "z" }, iterator.next().values()); assertFalse(iterator.hasNext()); try { iterator.next(); fail("NoSuchElementException expected"); } catch (final NoSuchElementException e) { // expected } } @Test public void testLineFeedEndings() throws IOException { final String code = "foo\nbaar,\nhello,world\n,kanu"; try (final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT)) { final List<CSVRecord> records = parser.getRecords(); assertEquals(4, records.size()); } } @Test public void testMappedButNotSetAsOutlook2007ContactExport() throws Exception { final Reader in = new StringReader("a,b,c\n1,2\nx,y,z"); final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader("A", "B", "C").withSkipHeaderRecord().parse(in) .iterator(); CSVRecord record; // 1st record record = records.next(); assertTrue(record.isMapped("A")); assertTrue(record.isMapped("B")); assertTrue(record.isMapped("C")); assertTrue(record.isSet("A")); assertTrue(record.isSet("B")); assertFalse(record.isSet("C")); assertEquals("1", record.get("A")); assertEquals("2", record.get("B")); assertFalse(record.isConsistent()); // 2nd record record = records.next(); assertTrue(record.isMapped("A")); assertTrue(record.isMapped("B")); assertTrue(record.isMapped("C")); assertTrue(record.isSet("A")); assertTrue(record.isSet("B")); assertTrue(record.isSet("C")); assertEquals("x", record.get("A")); assertEquals("y", record.get("B")); assertEquals("z", record.get("C")); assertTrue(record.isConsistent()); assertFalse(records.hasNext()); } @Test // TODO this may lead to strange behavior, throw an exception if iterator() has already been called? public void testMultipleIterators() throws Exception { try (final CSVParser parser = CSVParser.parse("a,b,c" + CR + "d,e,f", CSVFormat.DEFAULT)) { final Iterator<CSVRecord> itr1 = parser.iterator(); final Iterator<CSVRecord> itr2 = parser.iterator(); final CSVRecord first = itr1.next(); assertEquals("a", first.get(0)); assertEquals("b", first.get(1)); assertEquals("c", first.get(2)); final CSVRecord second = itr2.next(); assertEquals("d", second.get(0)); assertEquals("e", second.get(1)); assertEquals("f", second.get(2)); } } @Test(expected = IllegalArgumentException.class) public void testNewCSVParserNullReaderFormat() throws Exception { try (final CSVParser parser = new CSVParser(null, CSVFormat.DEFAULT)) { Assert.fail("This test should have thrown an exception."); } } @Test(expected = IllegalArgumentException.class) public void testNewCSVParserReaderNullFormat() throws Exception { try (final CSVParser parser = new CSVParser(new StringReader(""), null)) { Assert.fail("This test should have thrown an exception."); } } @Test public void testNoHeaderMap() throws Exception { try (final CSVParser parser = CSVParser.parse("a,b,c\n1,2,3\nx,y,z", CSVFormat.DEFAULT)) { Assert.assertNull(parser.getHeaderMap()); } } @Test(expected = IllegalArgumentException.class) public void testParseFileNullFormat() throws Exception { CSVParser.parse(new File(""), Charset.defaultCharset(), null); } @Test(expected = IllegalArgumentException.class) public void testParseNullFileFormat() throws Exception { CSVParser.parse((File) null, Charset.defaultCharset(), CSVFormat.DEFAULT); } @Test(expected = IllegalArgumentException.class) public void testParseNullStringFormat() throws Exception { CSVParser.parse((String) null, CSVFormat.DEFAULT); } @Test(expected = IllegalArgumentException.class) public void testParseNullUrlCharsetFormat() throws Exception { CSVParser.parse((File) null, Charset.defaultCharset(), CSVFormat.DEFAULT); } @Test(expected = IllegalArgumentException.class) public void testParserUrlNullCharsetFormat() throws Exception { try (final CSVParser parser = CSVParser.parse(new URL("http://commons.apache.org"), null, CSVFormat.DEFAULT)) { Assert.fail("This test should have thrown an exception."); } } @Test(expected = IllegalArgumentException.class) public void testParseStringNullFormat() throws Exception { CSVParser.parse("csv data", null); } @Test(expected = IllegalArgumentException.class) public void testParseUrlCharsetNullFormat() throws Exception { try (final CSVParser parser = CSVParser.parse(new URL("http://commons.apache.org"), Charset.defaultCharset(), null)) { Assert.fail("This test should have thrown an exception."); } } @Test public void testProvidedHeader() throws Exception { final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader("A", "B", "C").parse(in).iterator(); for (int i = 0; i < 3; i++) { assertTrue(records.hasNext()); final CSVRecord record = records.next(); assertTrue(record.isMapped("A")); assertTrue(record.isMapped("B")); assertTrue(record.isMapped("C")); assertFalse(record.isMapped("NOT MAPPED")); assertEquals(record.get(0), record.get("A")); assertEquals(record.get(1), record.get("B")); assertEquals(record.get(2), record.get("C")); } assertFalse(records.hasNext()); } @Test public void testProvidedHeaderAuto() throws Exception { final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); for (int i = 0; i < 2; i++) { assertTrue(records.hasNext()); final CSVRecord record = records.next(); assertTrue(record.isMapped("a")); assertTrue(record.isMapped("b")); assertTrue(record.isMapped("c")); assertFalse(record.isMapped("NOT MAPPED")); assertEquals(record.get(0), record.get("a")); assertEquals(record.get(1), record.get("b")); assertEquals(record.get(2), record.get("c")); } assertFalse(records.hasNext()); } @Test public void testRoundtrip() throws Exception { final StringWriter out = new StringWriter(); try (final CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT)) { final String input = "a,b,c\r\n1,2,3\r\nx,y,z\r\n"; for (final CSVRecord record : CSVParser.parse(input, CSVFormat.DEFAULT)) { printer.printRecord(record); } assertEquals(input, out.toString()); } } @Test public void testSkipAutoHeader() throws Exception { final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); final CSVRecord record = records.next(); assertEquals("1", record.get("a")); assertEquals("2", record.get("b")); assertEquals("3", record.get("c")); } @Test public void testSkipHeaderOverrideDuplicateHeaders() throws Exception { final Reader in = new StringReader("a,a,a\n1,2,3\nx,y,z"); final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader("X", "Y", "Z").withSkipHeaderRecord().parse(in) .iterator(); final CSVRecord record = records.next(); assertEquals("1", record.get("X")); assertEquals("2", record.get("Y")); assertEquals("3", record.get("Z")); } @Test public void testSkipSetAltHeaders() throws Exception { final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader("X", "Y", "Z").withSkipHeaderRecord().parse(in) .iterator(); final CSVRecord record = records.next(); assertEquals("1", record.get("X")); assertEquals("2", record.get("Y")); assertEquals("3", record.get("Z")); } @Test public void testSkipSetHeader() throws Exception { final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader("a", "b", "c").withSkipHeaderRecord().parse(in) .iterator(); final CSVRecord record = records.next(); assertEquals("1", record.get("a")); assertEquals("2", record.get("b")); assertEquals("3", record.get("c")); } @Test @Ignore public void testStartWithEmptyLinesThenHeaders() throws Exception { final String[] codes = { "\r\n\r\n\r\nhello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", "hello,\"\"\n\n\n" }; final String[][] res = { { "hello", "" }, { "" }, // Excel format does not ignore empty lines { "" } }; for (final String code : codes) { try (final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL)) { final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } } } @Test public void testTrailingDelimiter() throws Exception { final Reader in = new StringReader("a,a,a,\n\"1\",\"2\",\"3\",\nx,y,z,"); final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader("X", "Y", "Z").withSkipHeaderRecord() .withTrailingDelimiter().parse(in).iterator(); final CSVRecord record = records.next(); assertEquals("1", record.get("X")); assertEquals("2", record.get("Y")); assertEquals("3", record.get("Z")); Assert.assertEquals(3, record.size()); } @Test public void testTrim() throws Exception { final Reader in = new StringReader("a,a,a\n\" 1 \",\" 2 \",\" 3 \"\nx,y,z"); final Iterator<CSVRecord> records = CSVFormat.DEFAULT.withHeader("X", "Y", "Z").withSkipHeaderRecord() .withTrim().parse(in).iterator(); final CSVRecord record = records.next(); assertEquals("1", record.get("X")); assertEquals("2", record.get("Y")); assertEquals("3", record.get("Z")); Assert.assertEquals(3, record.size()); } @Test public void testIteratorSequenceBreaking() throws IOException { final String fiveRows = "1\n2\n3\n4\n5\n"; // Iterator hasNext() shouldn't break sequence CSVParser parser = CSVFormat.DEFAULT.parse(new StringReader(fiveRows)); int recordNumber = 0; Iterator<CSVRecord> iter = parser.iterator(); recordNumber = 0; while (iter.hasNext()) { CSVRecord record = iter.next(); recordNumber++; assertEquals(String.valueOf(recordNumber), record.get(0)); if (recordNumber >= 2) { break; } } iter.hasNext(); while (iter.hasNext()) { CSVRecord record = iter.next(); recordNumber++; assertEquals(String.valueOf(recordNumber), record.get(0)); } // Consecutive enhanced for loops shouldn't break sequence parser = CSVFormat.DEFAULT.parse(new StringReader(fiveRows)); recordNumber = 0; for (CSVRecord record : parser) { recordNumber++; assertEquals(String.valueOf(recordNumber), record.get(0)); if (recordNumber >= 2) { break; } } for (CSVRecord record : parser) { recordNumber++; assertEquals(String.valueOf(recordNumber), record.get(0)); } // Consecutive enhanced for loops with hasNext() peeking shouldn't break sequence parser = CSVFormat.DEFAULT.parse(new StringReader(fiveRows)); recordNumber = 0; for (CSVRecord record : parser) { recordNumber++; assertEquals(String.valueOf(recordNumber), record.get(0)); if (recordNumber >= 2) { break; } } parser.iterator().hasNext(); for (CSVRecord record : parser) { recordNumber++; assertEquals(String.valueOf(recordNumber), record.get(0)); } } private void validateLineNumbers(final String lineSeparator) throws IOException { try (final CSVParser parser = CSVParser.parse("a" + lineSeparator + "b" + lineSeparator + "c", CSVFormat.DEFAULT.withRecordSeparator(lineSeparator))) { assertEquals(0, parser.getCurrentLineNumber()); assertNotNull(parser.nextRecord()); assertEquals(1, parser.getCurrentLineNumber()); assertNotNull(parser.nextRecord()); assertEquals(2, parser.getCurrentLineNumber()); assertNotNull(parser.nextRecord()); // Still 2 because the last line is does not have EOL chars assertEquals(2, parser.getCurrentLineNumber()); assertNull(parser.nextRecord()); // Still 2 because the last line is does not have EOL chars assertEquals(2, parser.getCurrentLineNumber()); } } private void validateRecordNumbers(final String lineSeparator) throws IOException { try (final CSVParser parser = CSVParser.parse("a" + lineSeparator + "b" + lineSeparator + "c", CSVFormat.DEFAULT.withRecordSeparator(lineSeparator))) { CSVRecord record; assertEquals(0, parser.getRecordNumber()); assertNotNull(record = parser.nextRecord()); assertEquals(1, record.getRecordNumber()); assertEquals(1, parser.getRecordNumber()); assertNotNull(record = parser.nextRecord()); assertEquals(2, record.getRecordNumber()); assertEquals(2, parser.getRecordNumber()); assertNotNull(record = parser.nextRecord()); assertEquals(3, record.getRecordNumber()); assertEquals(3, parser.getRecordNumber()); assertNull(record = parser.nextRecord()); assertEquals(3, parser.getRecordNumber()); } } private void validateRecordPosition(final String lineSeparator) throws IOException { final String nl = lineSeparator; // used as linebreak in values for better distinction final String code = "a,b,c" + lineSeparator + "1,2,3" + lineSeparator + // to see if recordPosition correctly points to the enclosing quote "'A" + nl + "A','B" + nl + "B',CC" + lineSeparator + // unicode test... not very relevant while operating on strings instead of bytes, but for // completeness... "\u00c4,\u00d6,\u00dc" + lineSeparator + "EOF,EOF,EOF"; final CSVFormat format = CSVFormat.newFormat(',').withQuote('\'').withRecordSeparator(lineSeparator); CSVParser parser = CSVParser.parse(code, format); CSVRecord record; assertEquals(0, parser.getRecordNumber()); assertNotNull(record = parser.nextRecord()); assertEquals(1, record.getRecordNumber()); assertEquals(code.indexOf('a'), record.getCharacterPosition()); assertNotNull(record = parser.nextRecord()); assertEquals(2, record.getRecordNumber()); assertEquals(code.indexOf('1'), record.getCharacterPosition()); assertNotNull(record = parser.nextRecord()); final long positionRecord3 = record.getCharacterPosition(); assertEquals(3, record.getRecordNumber()); assertEquals(code.indexOf("'A"), record.getCharacterPosition()); assertEquals("A" + lineSeparator + "A", record.get(0)); assertEquals("B" + lineSeparator + "B", record.get(1)); assertEquals("CC", record.get(2)); assertNotNull(record = parser.nextRecord()); assertEquals(4, record.getRecordNumber()); assertEquals(code.indexOf('\u00c4'), record.getCharacterPosition()); assertNotNull(record = parser.nextRecord()); assertEquals(5, record.getRecordNumber()); assertEquals(code.indexOf("EOF"), record.getCharacterPosition()); parser.close(); // now try to read starting at record 3 parser = new CSVParser(new StringReader(code.substring((int) positionRecord3)), format, positionRecord3, 3); assertNotNull(record = parser.nextRecord()); assertEquals(3, record.getRecordNumber()); assertEquals(code.indexOf("'A"), record.getCharacterPosition()); assertEquals("A" + lineSeparator + "A", record.get(0)); assertEquals("B" + lineSeparator + "B", record.get(1)); assertEquals("CC", record.get(2)); assertNotNull(record = parser.nextRecord()); assertEquals(4, record.getRecordNumber()); assertEquals(code.indexOf('\u00c4'), record.getCharacterPosition()); assertEquals("\u00c4", record.get(0)); parser.close(); } }
[ { "be_test_class_file": "org/apache/commons/csv/CSVParser.java", "be_test_class_name": "org.apache.commons.csv.CSVParser", "be_test_function_name": "addRecordValue", "be_test_function_signature": "(Z)V", "line_numbers": [ "365", "366", "367", "368", "370", "371", "372" ], "method_line_rate": 0.8571428571428571 }, { "be_test_class_file": "org/apache/commons/csv/CSVParser.java", "be_test_class_name": "org.apache.commons.csv.CSVParser", "be_test_function_name": "close", "be_test_function_signature": "()V", "line_numbers": [ "382", "383", "385" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/csv/CSVParser.java", "be_test_class_name": "org.apache.commons.csv.CSVParser", "be_test_function_name": "initializeHeader", "be_test_function_signature": "()Ljava/util/Map;", "line_numbers": [ "464", "465", "466", "467", "471", "472", "474", "475", "476", "478", "479", "480", "482", "486", "487", "488", "489", "490", "491", "492", "495", "499" ], "method_line_rate": 0.18181818181818182 }, { "be_test_class_file": "org/apache/commons/csv/CSVParser.java", "be_test_class_name": "org.apache.commons.csv.CSVParser", "be_test_function_name": "nextRecord", "be_test_function_signature": "()Lorg/apache/commons/csv/CSVRecord;", "line_numbers": [ "585", "586", "587", "588", "590", "591", "592", "594", "595", "597", "598", "600", "601", "605", "607", "608", "610", "612", "613", "614", "616", "618", "620", "621", "622", "623", "626" ], "method_line_rate": 0.6296296296296297 } ]
public class DateAxisTests extends TestCase
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)); }
// 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 `test1472942` for the `DateAxis` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * A test for bug report 1472942. The DateFormat.equals() method is not * checking the range attribute. */
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);
177
test1472942
```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 `test1472942` for the `DateAxis` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * A test for bug report 1472942. The DateFormat.equals() method is not * checking the range attribute. */
167
// 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 `test1472942` for the `DateAxis` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * A test for bug report 1472942. The DateFormat.equals() method is not * checking the range attribute. */ public void test1472942() {
/** * A test for bug report 1472942. The DateFormat.equals() method is not * checking the range attribute. */
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 `test1472942` for the `DateAxis` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * A test for bug report 1472942. The DateFormat.equals() method is not * checking the range attribute. */ public void test1472942() { ```
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);
a1b40fbe5b39c99e9c2b6c383d6ad6251f96cb03758f7cb02efbc8852706bb0d
[ "org.jfree.chart.axis.junit.DateAxisTests::test1472942" ]
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 test1472942()
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": "equals", "be_test_function_signature": "(Ljava/lang/Object;)Z", "line_numbers": [ "1894", "1895", "1897", "1898", "1900", "1901", "1902", "1904", "1906", "1908", "1910", "1912", "1913", "1915" ], "method_line_rate": 0.5714285714285714 }, { "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": "setTickUnit", "be_test_function_signature": "(Lorg/jfree/chart/axis/DateTickUnit;ZZ)V", "line_numbers": [ "496", "497", "498", "500", "501", "504" ], "method_line_rate": 0.6666666666666666 } ]
public class JSTypeTest extends BaseJSTypeTestCase
public void testSupertypeOfProxiedFunctionTypes() { ObjectType fn1 = new FunctionBuilder(registry) .withParamsNode(new Node(Token.PARAM_LIST)) .withReturnType(NUMBER_TYPE) .build(); ObjectType fn2 = new FunctionBuilder(registry) .withParamsNode(new Node(Token.PARAM_LIST)) .withReturnType(STRING_TYPE) .build(); ObjectType p1 = new ProxyObjectType(registry, fn1); ObjectType p2 = new ProxyObjectType(registry, fn2); ObjectType supremum = new FunctionBuilder(registry) .withParamsNode(new Node(Token.PARAM_LIST)) .withReturnType(registry.createUnionType(STRING_TYPE, NUMBER_TYPE)) .build(); assertTypeEquals(fn1.getLeastSupertype(fn2), p1.getLeastSupertype(p2)); assertTypeEquals(supremum, fn1.getLeastSupertype(fn2)); assertTypeEquals(supremum, fn1.getLeastSupertype(p2)); assertTypeEquals(supremum, p1.getLeastSupertype(fn2)); assertTypeEquals(supremum, p1.getLeastSupertype(p2)); }
// public void testRecordTypeGreatestSubType8(); // public void testApplyOfDateMethod(); // public void testCallOfDateMethod(); // public void testFunctionTypeRepresentation(); // public void testFunctionTypeRelationships(); // public void testProxiedFunctionTypeRelationships(); // public void testFunctionSubTypeRelationships(); // public void testFunctionPrototypeAndImplicitPrototype1(); // public void testFunctionPrototypeAndImplicitPrototype2(); // public void testJSDocOnPrototypeProperty() throws Exception; // public void testVoidType() throws Exception; // public void testBooleanValueType() throws Exception; // public void testBooleanObjectType() throws Exception; // public void testEnumType() throws Exception; // public void testEnumElementType() throws Exception; // public void testStringEnumType() throws Exception; // public void testStringObjectEnumType() throws Exception; // public void testObjectType() throws Exception; // public void testGoogBar() throws Exception; // public void testObjectTypePropertiesCount() throws Exception; // public void testDefineProperties(); // public void testObjectTypePropertiesCountWithShadowing(); // public void testNamedGoogBar() throws Exception; // public void testPrototypeChaining() throws Exception; // public void testInstanceFunctionChaining() throws Exception; // @SuppressWarnings("checked") // public void testCanTestForEqualityWithCornerCases(); // public void testTestForEquality(); // private void compare(TernaryValue r, JSType t1, JSType t2); // private void assertCanTestForEqualityWith(JSType t1, JSType t2); // private void assertCannotTestForEqualityWith(JSType t1, JSType t2); // public void testSubtypingSimpleTypes() throws Exception; // public void testSubtypingObjectTopOfObjects() throws Exception; // public void testSubtypingFunctionPrototypeType() throws Exception; // public void testSubtypingFunctionFixedArgs() throws Exception; // public void testSubtypingFunctionMultipleFixedArgs() throws Exception; // public void testSubtypingFunctionFixedArgsNotMatching() throws Exception; // public void testSubtypingFunctionVariableArgsOneOnly() throws Exception; // public void testSubtypingFunctionVariableArgsBoth() throws Exception; // public void testSubtypingMostGeneralFunction() throws Exception; // private List<JSType> getTypesToTestForSymmetry(); // public void testSymmetryOfTestForEquality(); // public void testSymmetryOfLeastSupertype(); // public void testWeirdBug(); // public void testSymmetryOfGreatestSubtype(); // public void testReflexivityOfLeastSupertype(); // public void testReflexivityOfGreatestSubtype(); // public void testLeastSupertypeUnresolvedNamedType(); // public void testLeastSupertypeUnresolvedNamedType2(); // public void testLeastSupertypeUnresolvedNamedType3(); // public void testSubclassOfUnresolvedNamedType(); // public void testSupertypeOfProxiedFunctionTypes(); // public void testTypeOfThisIsProxied(); // public void testNamedTypeEquals(); // public void testNamedTypeEquals2(); // public void testForwardDeclaredNamedTypeEquals(); // public void testForwardDeclaredNamedType(); // public void testGreatestSubtypeSimpleTypes(); // public void testSubtypingDerivedExtendsNamedBaseType() throws Exception; // public void testNamedSubtypeChain() throws Exception; // public void testRecordSubtypeChain() throws Exception; // public void testRecordAndObjectChain2() throws Exception; // public void testRecordAndObjectChain3() throws Exception; // public void testNullableNamedTypeChain() throws Exception; // public void testEnumTypeChain() throws Exception; // public void testFunctionSubtypeChain() throws Exception; // public void testFunctionUnionSubtypeChain() throws Exception; // public void testConstructorSubtypeChain() throws Exception; // public void testGoogBarSubtypeChain() throws Exception; // public void testConstructorWithArgSubtypeChain() throws Exception; // public void testInterfaceInstanceSubtypeChain() throws Exception; // public void testInterfaceInheritanceSubtypeChain() throws Exception; // public void testAnonymousObjectChain() throws Exception; // public void testAnonymousEnumElementChain() throws Exception; // public void testTemplatizedArrayChain() throws Exception; // public void testTemplatizedArrayChain2() throws Exception; // public void testTemplatizedObjectChain() throws Exception; // public void testMixedTemplatizedTypeChain() throws Exception; // public void testTemplatizedTypeSubtypes(); // public void testTemplatizedTypeRelations() throws Exception; // public void verifySubtypeChain(List<JSType> typeChain) throws Exception; // public void verifySubtypeChain(List<JSType> typeChain, // boolean checkSubtyping) throws Exception; // JSType getNamedWrapper(String name, JSType jstype); // @SuppressWarnings("checked") // public void testRestrictedTypeGivenToBoolean(); // public void testRegisterProperty(); // public void testRegisterPropertyMemoization(); // public void testGreatestSubtypeWithProperty(); // public void testGoodSetPrototypeBasedOn(); // public void testLateSetPrototypeBasedOn(); // public void testGetTypeUnderEquality1(); // public void testGetTypesUnderEquality2(); // public void testGetTypesUnderEquality3(); // @SuppressWarnings("checked") // public void testGetTypesUnderEquality4(); // public void testGetTypesUnderEquality5(); // public void testGetTypesUnderEquality6(); // private void testGetTypeUnderEquality( // JSType t1, JSType t2, JSType t1Eq, JSType t2Eq); // @SuppressWarnings("checked") // public void testGetTypesUnderInequality1(); // @SuppressWarnings("checked") // public void testGetTypesUnderInequality2(); // @SuppressWarnings("checked") // public void testGetTypesUnderInequality3(); // @SuppressWarnings("checked") // public void testGetTypesUnderInequality4() throws Exception; // private void testGetTypesUnderInequality( // JSType t1, JSType t2, JSType t1Eq, JSType t2Eq); // public void testCreateRecordType() throws Exception; // public void testCreateOptionalType() throws Exception; // public void assertUnionContains(UnionType union, JSType type); // public void testCreateAnonymousObjectType() throws Exception; // public void testCreateAnonymousObjectType2() throws Exception; // public void testCreateObjectType() throws Exception; // @SuppressWarnings("checked") // public void testBug903110() throws Exception; // public void testBug904123() throws Exception; // private void assertTypeCanAssignToItself(JSType type); // public void testHasOwnProperty() throws Exception; // public void testNamedTypeHasOwnProperty() throws Exception; // public void testInterfaceHasOwnProperty() throws Exception; // public void testGetPropertyNames() throws Exception; // public void testGetAndSetJSDocInfoWithNamedType() throws Exception; // public void testGetAndSetJSDocInfoWithObjectTypes() throws Exception; // public void testGetAndSetJSDocInfoWithNoType() throws Exception; // public void testObjectGetSubTypes() throws Exception; // public void testImplementingType() throws Exception; // public void testIsTemplatedType() throws Exception; // public void testTemplatizedType() throws Exception; // public void testPartiallyTemplatizedType() throws Exception; // public void testCanCastTo(); // private static boolean containsType( // Iterable<? extends JSType> types, JSType type); // private static boolean assertTypeListEquals( // Iterable<? extends JSType> typeListA, // Iterable<? extends JSType> typeListB); // private ArrowType createArrowType(Node params); // @Override // public StaticSlot<JSType> getSlot(String name); // } // You are a professional Java test case writer, please create a test case named `testSupertypeOfProxiedFunctionTypes` for the `JSType` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests that Proxied FunctionTypes behave the same over getLeastSupertype and * getGreatestSubtype as non proxied FunctionTypes */
test/com/google/javascript/rhino/jstype/JSTypeTest.java
package com.google.javascript.rhino.jstype; import static com.google.javascript.rhino.jstype.TernaryValue.UNKNOWN; import com.google.common.base.Predicate; import com.google.javascript.rhino.ErrorReporter; import com.google.javascript.rhino.JSDocInfo; import java.io.Serializable; import java.util.Comparator;
JSType(JSTypeRegistry registry); JSType(JSTypeRegistry registry, TemplateTypeMap templateTypeMap); JSType getNativeType(JSTypeNative typeId); public JSDocInfo getJSDocInfo(); public String getDisplayName(); public boolean hasDisplayName(); public boolean hasProperty(String pname); public boolean isNoType(); public boolean isNoResolvedType(); public boolean isNoObjectType(); public final boolean isEmptyType(); public boolean isNumberObjectType(); public boolean isNumberValueType(); public boolean isFunctionPrototypeType(); public boolean isStringObjectType(); boolean isTheObjectType(); public boolean isStringValueType(); public final boolean isString(); public final boolean isNumber(); public boolean isArrayType(); public boolean isBooleanObjectType(); public boolean isBooleanValueType(); public boolean isRegexpType(); public boolean isDateType(); public boolean isNullType(); public boolean isVoidType(); public boolean isAllType(); public boolean isUnknownType(); public boolean isCheckedUnknownType(); public final boolean isUnionType(); public boolean isStruct(); public boolean isDict(); public UnionType toMaybeUnionType(); public final boolean isGlobalThisType(); public final boolean isFunctionType(); public FunctionType toMaybeFunctionType(); public static FunctionType toMaybeFunctionType(JSType type); public final boolean isEnumElementType(); public EnumElementType toMaybeEnumElementType(); public boolean isEnumType(); public EnumType toMaybeEnumType(); boolean isNamedType(); public boolean isRecordType(); RecordType toMaybeRecordType(); public final boolean isTemplatizedType(); public TemplatizedType toMaybeTemplatizedType(); public static TemplatizedType toMaybeTemplatizedType(JSType type); public final boolean isTemplateType(); public TemplateType toMaybeTemplateType(); public static TemplateType toMaybeTemplateType(JSType type); public boolean hasAnyTemplateTypes(); boolean hasAnyTemplateTypesInternal(); public TemplateTypeMap getTemplateTypeMap(); public void extendTemplateTypeMap(TemplateTypeMap otherMap); public boolean isObject(); public boolean isConstructor(); public boolean isNominalType(); public final boolean isNominalConstructor(); public boolean isInstanceType(); public boolean isInterface(); public boolean isOrdinaryFunction(); public final boolean isEquivalentTo(JSType that); public final boolean isInvariant(JSType that); public final boolean differsFrom(JSType that); boolean checkEquivalenceHelper( final JSType that, EquivalenceMethod eqMethod); private String getConcreteNominalTypeName(ObjectType objType); public static boolean isEquivalent(JSType typeA, JSType typeB); @Override public boolean equals(Object jsType); @Override public int hashCode(); public final boolean matchesInt32Context(); public final boolean matchesUint32Context(); public boolean matchesNumberContext(); public boolean matchesStringContext(); public boolean matchesObjectContext(); public JSType findPropertyType(String propertyName); public boolean canBeCalled(); public boolean canCastTo(JSType that); public JSType autoboxesTo(); public JSType unboxesTo(); public ObjectType toObjectType(); public JSType autobox(); public final ObjectType dereference(); public final boolean canTestForEqualityWith(JSType that); public TernaryValue testForEquality(JSType that); TernaryValue testForEqualityHelper(JSType aType, JSType bType); public final boolean canTestForShallowEqualityWith(JSType that); public boolean isNullable(); public JSType collapseUnion(); public JSType getLeastSupertype(JSType that); static JSType getLeastSupertype(JSType thisType, JSType thatType); public JSType getGreatestSubtype(JSType that); static JSType getGreatestSubtype(JSType thisType, JSType thatType); static JSType filterNoResolvedType(JSType type); public JSType getRestrictedTypeGivenToBooleanOutcome(boolean outcome); public abstract BooleanLiteralSet getPossibleToBooleanOutcomes(); public TypePair getTypesUnderEquality(JSType that); public TypePair getTypesUnderInequality(JSType that); public TypePair getTypesUnderShallowEquality(JSType that); public TypePair getTypesUnderShallowInequality(JSType that); public JSType restrictByNotNullOrUndefined(); public boolean isSubtype(JSType that); static boolean isSubtypeHelper(JSType thisType, JSType thatType); static boolean isExemptFromTemplateTypeInvariance(JSType type); public abstract <T> T visit(Visitor<T> visitor); abstract <T> T visit(RelationshipVisitor<T> visitor, JSType that); public final JSType resolve(ErrorReporter t, StaticScope<JSType> scope); abstract JSType resolveInternal(ErrorReporter t, StaticScope<JSType> scope); void setResolvedTypeInternal(JSType type); public final boolean isResolved(); public final void clearResolved(); static final JSType safeResolve( JSType type, ErrorReporter t, StaticScope<JSType> scope); public boolean setValidator(Predicate<JSType> validator); @Override public String toString(); public String toDebugHashCodeString(); public final String toAnnotationString(); abstract String toStringHelper(boolean forAnnotations); public void matchConstraint(JSType constraint); public TypePair(JSType typeA, JSType typeB); @Override public int compare(JSType t1, JSType t2);
4,782
testSupertypeOfProxiedFunctionTypes
```java public void testRecordTypeGreatestSubType8(); public void testApplyOfDateMethod(); public void testCallOfDateMethod(); public void testFunctionTypeRepresentation(); public void testFunctionTypeRelationships(); public void testProxiedFunctionTypeRelationships(); public void testFunctionSubTypeRelationships(); public void testFunctionPrototypeAndImplicitPrototype1(); public void testFunctionPrototypeAndImplicitPrototype2(); public void testJSDocOnPrototypeProperty() throws Exception; public void testVoidType() throws Exception; public void testBooleanValueType() throws Exception; public void testBooleanObjectType() throws Exception; public void testEnumType() throws Exception; public void testEnumElementType() throws Exception; public void testStringEnumType() throws Exception; public void testStringObjectEnumType() throws Exception; public void testObjectType() throws Exception; public void testGoogBar() throws Exception; public void testObjectTypePropertiesCount() throws Exception; public void testDefineProperties(); public void testObjectTypePropertiesCountWithShadowing(); public void testNamedGoogBar() throws Exception; public void testPrototypeChaining() throws Exception; public void testInstanceFunctionChaining() throws Exception; @SuppressWarnings("checked") public void testCanTestForEqualityWithCornerCases(); public void testTestForEquality(); private void compare(TernaryValue r, JSType t1, JSType t2); private void assertCanTestForEqualityWith(JSType t1, JSType t2); private void assertCannotTestForEqualityWith(JSType t1, JSType t2); public void testSubtypingSimpleTypes() throws Exception; public void testSubtypingObjectTopOfObjects() throws Exception; public void testSubtypingFunctionPrototypeType() throws Exception; public void testSubtypingFunctionFixedArgs() throws Exception; public void testSubtypingFunctionMultipleFixedArgs() throws Exception; public void testSubtypingFunctionFixedArgsNotMatching() throws Exception; public void testSubtypingFunctionVariableArgsOneOnly() throws Exception; public void testSubtypingFunctionVariableArgsBoth() throws Exception; public void testSubtypingMostGeneralFunction() throws Exception; private List<JSType> getTypesToTestForSymmetry(); public void testSymmetryOfTestForEquality(); public void testSymmetryOfLeastSupertype(); public void testWeirdBug(); public void testSymmetryOfGreatestSubtype(); public void testReflexivityOfLeastSupertype(); public void testReflexivityOfGreatestSubtype(); public void testLeastSupertypeUnresolvedNamedType(); public void testLeastSupertypeUnresolvedNamedType2(); public void testLeastSupertypeUnresolvedNamedType3(); public void testSubclassOfUnresolvedNamedType(); public void testSupertypeOfProxiedFunctionTypes(); public void testTypeOfThisIsProxied(); public void testNamedTypeEquals(); public void testNamedTypeEquals2(); public void testForwardDeclaredNamedTypeEquals(); public void testForwardDeclaredNamedType(); public void testGreatestSubtypeSimpleTypes(); public void testSubtypingDerivedExtendsNamedBaseType() throws Exception; public void testNamedSubtypeChain() throws Exception; public void testRecordSubtypeChain() throws Exception; public void testRecordAndObjectChain2() throws Exception; public void testRecordAndObjectChain3() throws Exception; public void testNullableNamedTypeChain() throws Exception; public void testEnumTypeChain() throws Exception; public void testFunctionSubtypeChain() throws Exception; public void testFunctionUnionSubtypeChain() throws Exception; public void testConstructorSubtypeChain() throws Exception; public void testGoogBarSubtypeChain() throws Exception; public void testConstructorWithArgSubtypeChain() throws Exception; public void testInterfaceInstanceSubtypeChain() throws Exception; public void testInterfaceInheritanceSubtypeChain() throws Exception; public void testAnonymousObjectChain() throws Exception; public void testAnonymousEnumElementChain() throws Exception; public void testTemplatizedArrayChain() throws Exception; public void testTemplatizedArrayChain2() throws Exception; public void testTemplatizedObjectChain() throws Exception; public void testMixedTemplatizedTypeChain() throws Exception; public void testTemplatizedTypeSubtypes(); public void testTemplatizedTypeRelations() throws Exception; public void verifySubtypeChain(List<JSType> typeChain) throws Exception; public void verifySubtypeChain(List<JSType> typeChain, boolean checkSubtyping) throws Exception; JSType getNamedWrapper(String name, JSType jstype); @SuppressWarnings("checked") public void testRestrictedTypeGivenToBoolean(); public void testRegisterProperty(); public void testRegisterPropertyMemoization(); public void testGreatestSubtypeWithProperty(); public void testGoodSetPrototypeBasedOn(); public void testLateSetPrototypeBasedOn(); public void testGetTypeUnderEquality1(); public void testGetTypesUnderEquality2(); public void testGetTypesUnderEquality3(); @SuppressWarnings("checked") public void testGetTypesUnderEquality4(); public void testGetTypesUnderEquality5(); public void testGetTypesUnderEquality6(); private void testGetTypeUnderEquality( JSType t1, JSType t2, JSType t1Eq, JSType t2Eq); @SuppressWarnings("checked") public void testGetTypesUnderInequality1(); @SuppressWarnings("checked") public void testGetTypesUnderInequality2(); @SuppressWarnings("checked") public void testGetTypesUnderInequality3(); @SuppressWarnings("checked") public void testGetTypesUnderInequality4() throws Exception; private void testGetTypesUnderInequality( JSType t1, JSType t2, JSType t1Eq, JSType t2Eq); public void testCreateRecordType() throws Exception; public void testCreateOptionalType() throws Exception; public void assertUnionContains(UnionType union, JSType type); public void testCreateAnonymousObjectType() throws Exception; public void testCreateAnonymousObjectType2() throws Exception; public void testCreateObjectType() throws Exception; @SuppressWarnings("checked") public void testBug903110() throws Exception; public void testBug904123() throws Exception; private void assertTypeCanAssignToItself(JSType type); public void testHasOwnProperty() throws Exception; public void testNamedTypeHasOwnProperty() throws Exception; public void testInterfaceHasOwnProperty() throws Exception; public void testGetPropertyNames() throws Exception; public void testGetAndSetJSDocInfoWithNamedType() throws Exception; public void testGetAndSetJSDocInfoWithObjectTypes() throws Exception; public void testGetAndSetJSDocInfoWithNoType() throws Exception; public void testObjectGetSubTypes() throws Exception; public void testImplementingType() throws Exception; public void testIsTemplatedType() throws Exception; public void testTemplatizedType() throws Exception; public void testPartiallyTemplatizedType() throws Exception; public void testCanCastTo(); private static boolean containsType( Iterable<? extends JSType> types, JSType type); private static boolean assertTypeListEquals( Iterable<? extends JSType> typeListA, Iterable<? extends JSType> typeListB); private ArrowType createArrowType(Node params); @Override public StaticSlot<JSType> getSlot(String name); } ``` You are a professional Java test case writer, please create a test case named `testSupertypeOfProxiedFunctionTypes` for the `JSType` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests that Proxied FunctionTypes behave the same over getLeastSupertype and * getGreatestSubtype as non proxied FunctionTypes */
4,758
// public void testRecordTypeGreatestSubType8(); // public void testApplyOfDateMethod(); // public void testCallOfDateMethod(); // public void testFunctionTypeRepresentation(); // public void testFunctionTypeRelationships(); // public void testProxiedFunctionTypeRelationships(); // public void testFunctionSubTypeRelationships(); // public void testFunctionPrototypeAndImplicitPrototype1(); // public void testFunctionPrototypeAndImplicitPrototype2(); // public void testJSDocOnPrototypeProperty() throws Exception; // public void testVoidType() throws Exception; // public void testBooleanValueType() throws Exception; // public void testBooleanObjectType() throws Exception; // public void testEnumType() throws Exception; // public void testEnumElementType() throws Exception; // public void testStringEnumType() throws Exception; // public void testStringObjectEnumType() throws Exception; // public void testObjectType() throws Exception; // public void testGoogBar() throws Exception; // public void testObjectTypePropertiesCount() throws Exception; // public void testDefineProperties(); // public void testObjectTypePropertiesCountWithShadowing(); // public void testNamedGoogBar() throws Exception; // public void testPrototypeChaining() throws Exception; // public void testInstanceFunctionChaining() throws Exception; // @SuppressWarnings("checked") // public void testCanTestForEqualityWithCornerCases(); // public void testTestForEquality(); // private void compare(TernaryValue r, JSType t1, JSType t2); // private void assertCanTestForEqualityWith(JSType t1, JSType t2); // private void assertCannotTestForEqualityWith(JSType t1, JSType t2); // public void testSubtypingSimpleTypes() throws Exception; // public void testSubtypingObjectTopOfObjects() throws Exception; // public void testSubtypingFunctionPrototypeType() throws Exception; // public void testSubtypingFunctionFixedArgs() throws Exception; // public void testSubtypingFunctionMultipleFixedArgs() throws Exception; // public void testSubtypingFunctionFixedArgsNotMatching() throws Exception; // public void testSubtypingFunctionVariableArgsOneOnly() throws Exception; // public void testSubtypingFunctionVariableArgsBoth() throws Exception; // public void testSubtypingMostGeneralFunction() throws Exception; // private List<JSType> getTypesToTestForSymmetry(); // public void testSymmetryOfTestForEquality(); // public void testSymmetryOfLeastSupertype(); // public void testWeirdBug(); // public void testSymmetryOfGreatestSubtype(); // public void testReflexivityOfLeastSupertype(); // public void testReflexivityOfGreatestSubtype(); // public void testLeastSupertypeUnresolvedNamedType(); // public void testLeastSupertypeUnresolvedNamedType2(); // public void testLeastSupertypeUnresolvedNamedType3(); // public void testSubclassOfUnresolvedNamedType(); // public void testSupertypeOfProxiedFunctionTypes(); // public void testTypeOfThisIsProxied(); // public void testNamedTypeEquals(); // public void testNamedTypeEquals2(); // public void testForwardDeclaredNamedTypeEquals(); // public void testForwardDeclaredNamedType(); // public void testGreatestSubtypeSimpleTypes(); // public void testSubtypingDerivedExtendsNamedBaseType() throws Exception; // public void testNamedSubtypeChain() throws Exception; // public void testRecordSubtypeChain() throws Exception; // public void testRecordAndObjectChain2() throws Exception; // public void testRecordAndObjectChain3() throws Exception; // public void testNullableNamedTypeChain() throws Exception; // public void testEnumTypeChain() throws Exception; // public void testFunctionSubtypeChain() throws Exception; // public void testFunctionUnionSubtypeChain() throws Exception; // public void testConstructorSubtypeChain() throws Exception; // public void testGoogBarSubtypeChain() throws Exception; // public void testConstructorWithArgSubtypeChain() throws Exception; // public void testInterfaceInstanceSubtypeChain() throws Exception; // public void testInterfaceInheritanceSubtypeChain() throws Exception; // public void testAnonymousObjectChain() throws Exception; // public void testAnonymousEnumElementChain() throws Exception; // public void testTemplatizedArrayChain() throws Exception; // public void testTemplatizedArrayChain2() throws Exception; // public void testTemplatizedObjectChain() throws Exception; // public void testMixedTemplatizedTypeChain() throws Exception; // public void testTemplatizedTypeSubtypes(); // public void testTemplatizedTypeRelations() throws Exception; // public void verifySubtypeChain(List<JSType> typeChain) throws Exception; // public void verifySubtypeChain(List<JSType> typeChain, // boolean checkSubtyping) throws Exception; // JSType getNamedWrapper(String name, JSType jstype); // @SuppressWarnings("checked") // public void testRestrictedTypeGivenToBoolean(); // public void testRegisterProperty(); // public void testRegisterPropertyMemoization(); // public void testGreatestSubtypeWithProperty(); // public void testGoodSetPrototypeBasedOn(); // public void testLateSetPrototypeBasedOn(); // public void testGetTypeUnderEquality1(); // public void testGetTypesUnderEquality2(); // public void testGetTypesUnderEquality3(); // @SuppressWarnings("checked") // public void testGetTypesUnderEquality4(); // public void testGetTypesUnderEquality5(); // public void testGetTypesUnderEquality6(); // private void testGetTypeUnderEquality( // JSType t1, JSType t2, JSType t1Eq, JSType t2Eq); // @SuppressWarnings("checked") // public void testGetTypesUnderInequality1(); // @SuppressWarnings("checked") // public void testGetTypesUnderInequality2(); // @SuppressWarnings("checked") // public void testGetTypesUnderInequality3(); // @SuppressWarnings("checked") // public void testGetTypesUnderInequality4() throws Exception; // private void testGetTypesUnderInequality( // JSType t1, JSType t2, JSType t1Eq, JSType t2Eq); // public void testCreateRecordType() throws Exception; // public void testCreateOptionalType() throws Exception; // public void assertUnionContains(UnionType union, JSType type); // public void testCreateAnonymousObjectType() throws Exception; // public void testCreateAnonymousObjectType2() throws Exception; // public void testCreateObjectType() throws Exception; // @SuppressWarnings("checked") // public void testBug903110() throws Exception; // public void testBug904123() throws Exception; // private void assertTypeCanAssignToItself(JSType type); // public void testHasOwnProperty() throws Exception; // public void testNamedTypeHasOwnProperty() throws Exception; // public void testInterfaceHasOwnProperty() throws Exception; // public void testGetPropertyNames() throws Exception; // public void testGetAndSetJSDocInfoWithNamedType() throws Exception; // public void testGetAndSetJSDocInfoWithObjectTypes() throws Exception; // public void testGetAndSetJSDocInfoWithNoType() throws Exception; // public void testObjectGetSubTypes() throws Exception; // public void testImplementingType() throws Exception; // public void testIsTemplatedType() throws Exception; // public void testTemplatizedType() throws Exception; // public void testPartiallyTemplatizedType() throws Exception; // public void testCanCastTo(); // private static boolean containsType( // Iterable<? extends JSType> types, JSType type); // private static boolean assertTypeListEquals( // Iterable<? extends JSType> typeListA, // Iterable<? extends JSType> typeListB); // private ArrowType createArrowType(Node params); // @Override // public StaticSlot<JSType> getSlot(String name); // } // You are a professional Java test case writer, please create a test case named `testSupertypeOfProxiedFunctionTypes` for the `JSType` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests that Proxied FunctionTypes behave the same over getLeastSupertype and * getGreatestSubtype as non proxied FunctionTypes */ public void testSupertypeOfProxiedFunctionTypes() {
/** * Tests that Proxied FunctionTypes behave the same over getLeastSupertype and * getGreatestSubtype as non proxied FunctionTypes */
107
com.google.javascript.rhino.jstype.JSType
test
```java public void testRecordTypeGreatestSubType8(); public void testApplyOfDateMethod(); public void testCallOfDateMethod(); public void testFunctionTypeRepresentation(); public void testFunctionTypeRelationships(); public void testProxiedFunctionTypeRelationships(); public void testFunctionSubTypeRelationships(); public void testFunctionPrototypeAndImplicitPrototype1(); public void testFunctionPrototypeAndImplicitPrototype2(); public void testJSDocOnPrototypeProperty() throws Exception; public void testVoidType() throws Exception; public void testBooleanValueType() throws Exception; public void testBooleanObjectType() throws Exception; public void testEnumType() throws Exception; public void testEnumElementType() throws Exception; public void testStringEnumType() throws Exception; public void testStringObjectEnumType() throws Exception; public void testObjectType() throws Exception; public void testGoogBar() throws Exception; public void testObjectTypePropertiesCount() throws Exception; public void testDefineProperties(); public void testObjectTypePropertiesCountWithShadowing(); public void testNamedGoogBar() throws Exception; public void testPrototypeChaining() throws Exception; public void testInstanceFunctionChaining() throws Exception; @SuppressWarnings("checked") public void testCanTestForEqualityWithCornerCases(); public void testTestForEquality(); private void compare(TernaryValue r, JSType t1, JSType t2); private void assertCanTestForEqualityWith(JSType t1, JSType t2); private void assertCannotTestForEqualityWith(JSType t1, JSType t2); public void testSubtypingSimpleTypes() throws Exception; public void testSubtypingObjectTopOfObjects() throws Exception; public void testSubtypingFunctionPrototypeType() throws Exception; public void testSubtypingFunctionFixedArgs() throws Exception; public void testSubtypingFunctionMultipleFixedArgs() throws Exception; public void testSubtypingFunctionFixedArgsNotMatching() throws Exception; public void testSubtypingFunctionVariableArgsOneOnly() throws Exception; public void testSubtypingFunctionVariableArgsBoth() throws Exception; public void testSubtypingMostGeneralFunction() throws Exception; private List<JSType> getTypesToTestForSymmetry(); public void testSymmetryOfTestForEquality(); public void testSymmetryOfLeastSupertype(); public void testWeirdBug(); public void testSymmetryOfGreatestSubtype(); public void testReflexivityOfLeastSupertype(); public void testReflexivityOfGreatestSubtype(); public void testLeastSupertypeUnresolvedNamedType(); public void testLeastSupertypeUnresolvedNamedType2(); public void testLeastSupertypeUnresolvedNamedType3(); public void testSubclassOfUnresolvedNamedType(); public void testSupertypeOfProxiedFunctionTypes(); public void testTypeOfThisIsProxied(); public void testNamedTypeEquals(); public void testNamedTypeEquals2(); public void testForwardDeclaredNamedTypeEquals(); public void testForwardDeclaredNamedType(); public void testGreatestSubtypeSimpleTypes(); public void testSubtypingDerivedExtendsNamedBaseType() throws Exception; public void testNamedSubtypeChain() throws Exception; public void testRecordSubtypeChain() throws Exception; public void testRecordAndObjectChain2() throws Exception; public void testRecordAndObjectChain3() throws Exception; public void testNullableNamedTypeChain() throws Exception; public void testEnumTypeChain() throws Exception; public void testFunctionSubtypeChain() throws Exception; public void testFunctionUnionSubtypeChain() throws Exception; public void testConstructorSubtypeChain() throws Exception; public void testGoogBarSubtypeChain() throws Exception; public void testConstructorWithArgSubtypeChain() throws Exception; public void testInterfaceInstanceSubtypeChain() throws Exception; public void testInterfaceInheritanceSubtypeChain() throws Exception; public void testAnonymousObjectChain() throws Exception; public void testAnonymousEnumElementChain() throws Exception; public void testTemplatizedArrayChain() throws Exception; public void testTemplatizedArrayChain2() throws Exception; public void testTemplatizedObjectChain() throws Exception; public void testMixedTemplatizedTypeChain() throws Exception; public void testTemplatizedTypeSubtypes(); public void testTemplatizedTypeRelations() throws Exception; public void verifySubtypeChain(List<JSType> typeChain) throws Exception; public void verifySubtypeChain(List<JSType> typeChain, boolean checkSubtyping) throws Exception; JSType getNamedWrapper(String name, JSType jstype); @SuppressWarnings("checked") public void testRestrictedTypeGivenToBoolean(); public void testRegisterProperty(); public void testRegisterPropertyMemoization(); public void testGreatestSubtypeWithProperty(); public void testGoodSetPrototypeBasedOn(); public void testLateSetPrototypeBasedOn(); public void testGetTypeUnderEquality1(); public void testGetTypesUnderEquality2(); public void testGetTypesUnderEquality3(); @SuppressWarnings("checked") public void testGetTypesUnderEquality4(); public void testGetTypesUnderEquality5(); public void testGetTypesUnderEquality6(); private void testGetTypeUnderEquality( JSType t1, JSType t2, JSType t1Eq, JSType t2Eq); @SuppressWarnings("checked") public void testGetTypesUnderInequality1(); @SuppressWarnings("checked") public void testGetTypesUnderInequality2(); @SuppressWarnings("checked") public void testGetTypesUnderInequality3(); @SuppressWarnings("checked") public void testGetTypesUnderInequality4() throws Exception; private void testGetTypesUnderInequality( JSType t1, JSType t2, JSType t1Eq, JSType t2Eq); public void testCreateRecordType() throws Exception; public void testCreateOptionalType() throws Exception; public void assertUnionContains(UnionType union, JSType type); public void testCreateAnonymousObjectType() throws Exception; public void testCreateAnonymousObjectType2() throws Exception; public void testCreateObjectType() throws Exception; @SuppressWarnings("checked") public void testBug903110() throws Exception; public void testBug904123() throws Exception; private void assertTypeCanAssignToItself(JSType type); public void testHasOwnProperty() throws Exception; public void testNamedTypeHasOwnProperty() throws Exception; public void testInterfaceHasOwnProperty() throws Exception; public void testGetPropertyNames() throws Exception; public void testGetAndSetJSDocInfoWithNamedType() throws Exception; public void testGetAndSetJSDocInfoWithObjectTypes() throws Exception; public void testGetAndSetJSDocInfoWithNoType() throws Exception; public void testObjectGetSubTypes() throws Exception; public void testImplementingType() throws Exception; public void testIsTemplatedType() throws Exception; public void testTemplatizedType() throws Exception; public void testPartiallyTemplatizedType() throws Exception; public void testCanCastTo(); private static boolean containsType( Iterable<? extends JSType> types, JSType type); private static boolean assertTypeListEquals( Iterable<? extends JSType> typeListA, Iterable<? extends JSType> typeListB); private ArrowType createArrowType(Node params); @Override public StaticSlot<JSType> getSlot(String name); } ``` You are a professional Java test case writer, please create a test case named `testSupertypeOfProxiedFunctionTypes` for the `JSType` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests that Proxied FunctionTypes behave the same over getLeastSupertype and * getGreatestSubtype as non proxied FunctionTypes */ public void testSupertypeOfProxiedFunctionTypes() { ```
public abstract class JSType implements Serializable
package com.google.javascript.rhino.jstype; import static com.google.javascript.rhino.jstype.TernaryValue.FALSE; import static com.google.javascript.rhino.jstype.TernaryValue.TRUE; import static com.google.javascript.rhino.jstype.TernaryValue.UNKNOWN; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.JSDocInfo.Visibility; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.SimpleErrorReporter; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.JSType.TypePair; import com.google.javascript.rhino.jstype.RecordTypeBuilder.RecordProperty; import com.google.javascript.rhino.testing.AbstractStaticScope; import com.google.javascript.rhino.testing.Asserts; import com.google.javascript.rhino.testing.BaseJSTypeTestCase; import com.google.javascript.rhino.testing.MapBasedScope; import java.util.HashMap; import java.util.List; import java.util.Map;
@Override protected void setUp() throws Exception; public void testUniversalConstructorType() throws Exception; public void testNoObjectType() throws Exception; public void testNoType() throws Exception; public void testNoResolvedType() throws Exception; public void testArrayType() throws Exception; public void testUnknownType() throws Exception; public void testCheckedUnknownType() throws Exception; public void testAllType() throws Exception; public void testTheObjectType() throws Exception; public void testNumberObjectType() throws Exception; public void testNumberValueType() throws Exception; public void testNullType() throws Exception; public void testDateType() throws Exception; public void testRegExpType() throws Exception; public void testStringObjectType() throws Exception; public void testStringValueType() throws Exception; private void assertPropertyTypeDeclared(ObjectType ownerType, String prop); private void assertPropertyTypeInferred(ObjectType ownerType, String prop); private void assertPropertyTypeUnknown(ObjectType ownerType, String prop); private void assertReturnTypeEquals(JSType expectedReturnType, JSType function); public void testRecordType() throws Exception; public void testFunctionInstanceType() throws Exception; public void testFunctionType() throws Exception; public void testRecordTypeSubtyping(); public void testRecordTypeSubtypingWithInferredProperties(); public void testRecordTypeLeastSuperType1(); public void testRecordTypeLeastSuperType2(); public void testRecordTypeLeastSuperType3(); public void testRecordTypeLeastSuperType4(); public void testRecordTypeGreatestSubType1(); public void testRecordTypeGreatestSubType2(); public void testRecordTypeGreatestSubType3(); public void testRecordTypeGreatestSubType4(); public void testRecordTypeGreatestSubType5(); public void testRecordTypeGreatestSubType6(); public void testRecordTypeGreatestSubType7(); public void testRecordTypeGreatestSubType8(); public void testApplyOfDateMethod(); public void testCallOfDateMethod(); public void testFunctionTypeRepresentation(); public void testFunctionTypeRelationships(); public void testProxiedFunctionTypeRelationships(); public void testFunctionSubTypeRelationships(); public void testFunctionPrototypeAndImplicitPrototype1(); public void testFunctionPrototypeAndImplicitPrototype2(); public void testJSDocOnPrototypeProperty() throws Exception; public void testVoidType() throws Exception; public void testBooleanValueType() throws Exception; public void testBooleanObjectType() throws Exception; public void testEnumType() throws Exception; public void testEnumElementType() throws Exception; public void testStringEnumType() throws Exception; public void testStringObjectEnumType() throws Exception; public void testObjectType() throws Exception; public void testGoogBar() throws Exception; public void testObjectTypePropertiesCount() throws Exception; public void testDefineProperties(); public void testObjectTypePropertiesCountWithShadowing(); public void testNamedGoogBar() throws Exception; public void testPrototypeChaining() throws Exception; public void testInstanceFunctionChaining() throws Exception; @SuppressWarnings("checked") public void testCanTestForEqualityWithCornerCases(); public void testTestForEquality(); private void compare(TernaryValue r, JSType t1, JSType t2); private void assertCanTestForEqualityWith(JSType t1, JSType t2); private void assertCannotTestForEqualityWith(JSType t1, JSType t2); public void testSubtypingSimpleTypes() throws Exception; public void testSubtypingObjectTopOfObjects() throws Exception; public void testSubtypingFunctionPrototypeType() throws Exception; public void testSubtypingFunctionFixedArgs() throws Exception; public void testSubtypingFunctionMultipleFixedArgs() throws Exception; public void testSubtypingFunctionFixedArgsNotMatching() throws Exception; public void testSubtypingFunctionVariableArgsOneOnly() throws Exception; public void testSubtypingFunctionVariableArgsBoth() throws Exception; public void testSubtypingMostGeneralFunction() throws Exception; private List<JSType> getTypesToTestForSymmetry(); public void testSymmetryOfTestForEquality(); public void testSymmetryOfLeastSupertype(); public void testWeirdBug(); public void testSymmetryOfGreatestSubtype(); public void testReflexivityOfLeastSupertype(); public void testReflexivityOfGreatestSubtype(); public void testLeastSupertypeUnresolvedNamedType(); public void testLeastSupertypeUnresolvedNamedType2(); public void testLeastSupertypeUnresolvedNamedType3(); public void testSubclassOfUnresolvedNamedType(); public void testSupertypeOfProxiedFunctionTypes(); public void testTypeOfThisIsProxied(); public void testNamedTypeEquals(); public void testNamedTypeEquals2(); public void testForwardDeclaredNamedTypeEquals(); public void testForwardDeclaredNamedType(); public void testGreatestSubtypeSimpleTypes(); public void testSubtypingDerivedExtendsNamedBaseType() throws Exception; public void testNamedSubtypeChain() throws Exception; public void testRecordSubtypeChain() throws Exception; public void testRecordAndObjectChain2() throws Exception; public void testRecordAndObjectChain3() throws Exception; public void testNullableNamedTypeChain() throws Exception; public void testEnumTypeChain() throws Exception; public void testFunctionSubtypeChain() throws Exception; public void testFunctionUnionSubtypeChain() throws Exception; public void testConstructorSubtypeChain() throws Exception; public void testGoogBarSubtypeChain() throws Exception; public void testConstructorWithArgSubtypeChain() throws Exception; public void testInterfaceInstanceSubtypeChain() throws Exception; public void testInterfaceInheritanceSubtypeChain() throws Exception; public void testAnonymousObjectChain() throws Exception; public void testAnonymousEnumElementChain() throws Exception; public void testTemplatizedArrayChain() throws Exception; public void testTemplatizedArrayChain2() throws Exception; public void testTemplatizedObjectChain() throws Exception; public void testMixedTemplatizedTypeChain() throws Exception; public void testTemplatizedTypeSubtypes(); public void testTemplatizedTypeRelations() throws Exception; public void verifySubtypeChain(List<JSType> typeChain) throws Exception; public void verifySubtypeChain(List<JSType> typeChain, boolean checkSubtyping) throws Exception; JSType getNamedWrapper(String name, JSType jstype); @SuppressWarnings("checked") public void testRestrictedTypeGivenToBoolean(); public void testRegisterProperty(); public void testRegisterPropertyMemoization(); public void testGreatestSubtypeWithProperty(); public void testGoodSetPrototypeBasedOn(); public void testLateSetPrototypeBasedOn(); public void testGetTypeUnderEquality1(); public void testGetTypesUnderEquality2(); public void testGetTypesUnderEquality3(); @SuppressWarnings("checked") public void testGetTypesUnderEquality4(); public void testGetTypesUnderEquality5(); public void testGetTypesUnderEquality6(); private void testGetTypeUnderEquality( JSType t1, JSType t2, JSType t1Eq, JSType t2Eq); @SuppressWarnings("checked") public void testGetTypesUnderInequality1(); @SuppressWarnings("checked") public void testGetTypesUnderInequality2(); @SuppressWarnings("checked") public void testGetTypesUnderInequality3(); @SuppressWarnings("checked") public void testGetTypesUnderInequality4() throws Exception; private void testGetTypesUnderInequality( JSType t1, JSType t2, JSType t1Eq, JSType t2Eq); public void testCreateRecordType() throws Exception; public void testCreateOptionalType() throws Exception; public void assertUnionContains(UnionType union, JSType type); public void testCreateAnonymousObjectType() throws Exception; public void testCreateAnonymousObjectType2() throws Exception; public void testCreateObjectType() throws Exception; @SuppressWarnings("checked") public void testBug903110() throws Exception; public void testBug904123() throws Exception; private void assertTypeCanAssignToItself(JSType type); public void testHasOwnProperty() throws Exception; public void testNamedTypeHasOwnProperty() throws Exception; public void testInterfaceHasOwnProperty() throws Exception; public void testGetPropertyNames() throws Exception; public void testGetAndSetJSDocInfoWithNamedType() throws Exception; public void testGetAndSetJSDocInfoWithObjectTypes() throws Exception; public void testGetAndSetJSDocInfoWithNoType() throws Exception; public void testObjectGetSubTypes() throws Exception; public void testImplementingType() throws Exception; public void testIsTemplatedType() throws Exception; public void testTemplatizedType() throws Exception; public void testPartiallyTemplatizedType() throws Exception; public void testCanCastTo(); private static boolean containsType( Iterable<? extends JSType> types, JSType type); private static boolean assertTypeListEquals( Iterable<? extends JSType> typeListA, Iterable<? extends JSType> typeListB); private ArrowType createArrowType(Node params); @Override public StaticSlot<JSType> getSlot(String name);
a1b9e5546049bf5fe45db5108c8cdfa3ee06ef06d5a875ae2e2caf89080af59e
[ "com.google.javascript.rhino.jstype.JSTypeTest::testSupertypeOfProxiedFunctionTypes" ]
private static final long serialVersionUID = 1L; private boolean resolved = false; private JSType resolveResult = null; protected TemplateTypeMap templateTypeMap; private boolean inTemplatedCheckVisit = false; private static final CanCastToVisitor CAN_CAST_TO_VISITOR = new CanCastToVisitor(); public static final String UNKNOWN_NAME = "Unknown class name"; public static final String NOT_A_CLASS = "Not declared as a constructor"; public static final String NOT_A_TYPE = "Not declared as a type name"; public static final String EMPTY_TYPE_COMPONENT = "Named type with empty name component"; static final Comparator<JSType> ALPHA = new Comparator<JSType>() { @Override public int compare(JSType t1, JSType t2) { return t1.toString().compareTo(t2.toString()); } }; public static final int ENUMDECL = 1; public static final int NOT_ENUMDECL = 0; final JSTypeRegistry registry;
public void testSupertypeOfProxiedFunctionTypes()
private FunctionType dateMethod; private FunctionType functionType; private NamedType unresolvedNamedType; private FunctionType googBar; private FunctionType googSubBar; private FunctionType googSubSubBar; private ObjectType googBarInst; private ObjectType googSubBarInst; private ObjectType googSubSubBarInst; private NamedType namedGoogBar; private ObjectType subclassOfUnresolvedNamedType; private FunctionType subclassCtor; private FunctionType interfaceType; private ObjectType interfaceInstType; private FunctionType subInterfaceType; private ObjectType subInterfaceInstType; private JSType recordType; private EnumType enumType; private EnumElementType elementsType; private NamedType forwardDeclaredNamedType; private static final StaticScope<JSType> EMPTY_SCOPE = MapBasedScope.emptyScope(); private List<JSType> types;
Closure
/* * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Nick Santos * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package com.google.javascript.rhino.jstype; import static com.google.javascript.rhino.jstype.TernaryValue.FALSE; import static com.google.javascript.rhino.jstype.TernaryValue.TRUE; import static com.google.javascript.rhino.jstype.TernaryValue.UNKNOWN; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.JSDocInfo.Visibility; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.SimpleErrorReporter; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.jstype.JSType.TypePair; import com.google.javascript.rhino.jstype.RecordTypeBuilder.RecordProperty; import com.google.javascript.rhino.testing.AbstractStaticScope; import com.google.javascript.rhino.testing.Asserts; import com.google.javascript.rhino.testing.BaseJSTypeTestCase; import com.google.javascript.rhino.testing.MapBasedScope; import java.util.HashMap; import java.util.List; import java.util.Map; // TODO(nicksantos): Split some of this up into per-class unit tests. public class JSTypeTest extends BaseJSTypeTestCase { private FunctionType dateMethod; private FunctionType functionType; private NamedType unresolvedNamedType; private FunctionType googBar; private FunctionType googSubBar; private FunctionType googSubSubBar; private ObjectType googBarInst; private ObjectType googSubBarInst; private ObjectType googSubSubBarInst; private NamedType namedGoogBar; private ObjectType subclassOfUnresolvedNamedType; private FunctionType subclassCtor; private FunctionType interfaceType; private ObjectType interfaceInstType; private FunctionType subInterfaceType; private ObjectType subInterfaceInstType; private JSType recordType; private EnumType enumType; private EnumElementType elementsType; private NamedType forwardDeclaredNamedType; private static final StaticScope<JSType> EMPTY_SCOPE = MapBasedScope.emptyScope(); /** * A non exhaustive list of representative types used to test simple * properties that should hold for all types (such as the reflexivity * of subtyping). */ private List<JSType> types; @Override protected void setUp() throws Exception { super.setUp(); RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); recordType = builder.build(); enumType = new EnumType(registry, "Enum", null, NUMBER_TYPE); elementsType = enumType.getElementsType(); functionType = new FunctionBuilder(registry) .withReturnType(NUMBER_TYPE) .build(); dateMethod = new FunctionBuilder(registry) .withParamsNode(new Node(Token.PARAM_LIST)) .withReturnType(NUMBER_TYPE) .withTypeOfThis(DATE_TYPE) .build(); unresolvedNamedType = new NamedType(registry, "not.resolved.named.type", null, -1, -1); namedGoogBar = new NamedType(registry, "goog.Bar", null, -1, -1); subclassCtor = new FunctionType(registry, null, null, createArrowType(null), null, null, true, false); subclassCtor.setPrototypeBasedOn(unresolvedNamedType); subclassOfUnresolvedNamedType = subclassCtor.getInstanceType(); interfaceType = FunctionType.forInterface(registry, "Interface", null, registry.createTemplateTypeMap(null, null)); interfaceInstType = interfaceType.getInstanceType(); subInterfaceType = FunctionType.forInterface( registry, "SubInterface", null, registry.createTemplateTypeMap(null, null)); subInterfaceType.setExtendedInterfaces( Lists.<ObjectType>newArrayList(interfaceInstType)); subInterfaceInstType = subInterfaceType.getInstanceType(); googBar = registry.createConstructorType( "goog.Bar", null, null, null, null); googBar.getPrototype().defineDeclaredProperty("date", DATE_TYPE, null); googBar.setImplementedInterfaces( Lists.<ObjectType>newArrayList(interfaceInstType)); googBarInst = googBar.getInstanceType(); googSubBar = registry.createConstructorType( "googSubBar", null, null, null, null); googSubBar.setPrototypeBasedOn(googBar.getInstanceType()); googSubBarInst = googSubBar.getInstanceType(); googSubSubBar = registry.createConstructorType( "googSubSubBar", null, null, null, null); googSubSubBar.setPrototypeBasedOn(googSubBar.getInstanceType()); googSubSubBarInst = googSubSubBar.getInstanceType(); final ObjectType googObject = registry.createAnonymousObjectType(null); googObject.defineDeclaredProperty("Bar", googBar, null); namedGoogBar.resolve(null, new AbstractStaticScope<JSType>() { @Override public StaticSlot<JSType> getSlot(String name) { if ("goog".equals(name)) { return new SimpleSlot("goog", googObject, false); } else { return null; } } }); assertNotNull(namedGoogBar.getImplicitPrototype()); forwardDeclaredNamedType = new NamedType(registry, "forwardDeclared", "source", 1, 0); registry.forwardDeclareType("forwardDeclared"); forwardDeclaredNamedType.resolve( new SimpleErrorReporter(), EMPTY_SCOPE); types = ImmutableList.of( NO_OBJECT_TYPE, NO_RESOLVED_TYPE, NO_TYPE, BOOLEAN_OBJECT_TYPE, BOOLEAN_TYPE, STRING_OBJECT_TYPE, STRING_TYPE, VOID_TYPE, UNKNOWN_TYPE, NULL_TYPE, NUMBER_OBJECT_TYPE, NUMBER_TYPE, DATE_TYPE, ERROR_TYPE, SYNTAX_ERROR_TYPE, dateMethod, functionType, unresolvedNamedType, googBar, googSubBar, googSubSubBar, namedGoogBar, googBar.getInstanceType(), subclassOfUnresolvedNamedType, subclassCtor, recordType, enumType, elementsType, googBar, googSubBar, forwardDeclaredNamedType); } /** * Tests the behavior of the top constructor type. */ public void testUniversalConstructorType() throws Exception { // isXxx assertFalse(U2U_CONSTRUCTOR_TYPE.isNoObjectType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isNoType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isArrayType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isBooleanValueType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isDateType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isEnumElementType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isNullType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isNamedType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isNullType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isNumber()); assertFalse(U2U_CONSTRUCTOR_TYPE.isNumberObjectType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isNumberValueType()); assertTrue(U2U_CONSTRUCTOR_TYPE.isObject()); assertFalse(U2U_CONSTRUCTOR_TYPE.isFunctionPrototypeType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isRegexpType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isString()); assertFalse(U2U_CONSTRUCTOR_TYPE.isStringObjectType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isStringValueType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isEnumType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isUnionType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isStruct()); assertFalse(U2U_CONSTRUCTOR_TYPE.isDict()); assertFalse(U2U_CONSTRUCTOR_TYPE.isAllType()); assertFalse(U2U_CONSTRUCTOR_TYPE.isVoidType()); assertTrue(U2U_CONSTRUCTOR_TYPE.isConstructor()); assertTrue(U2U_CONSTRUCTOR_TYPE.isInstanceType()); // isSubtype assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(NO_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(DATE_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(functionType)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(recordType)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(NULL_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(STRING_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(ALL_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE.isSubtype(VOID_TYPE)); // canTestForEqualityWith assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(NO_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(NO_OBJECT_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(ALL_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(ARRAY_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(BOOLEAN_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(BOOLEAN_OBJECT_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(DATE_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(EVAL_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(functionType)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(recordType)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(NULL_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(NUMBER_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(OBJECT_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(URI_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(RANGE_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(REFERENCE_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(REGEXP_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(STRING_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(STRING_OBJECT_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(SYNTAX_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(TYPE_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForEqualityWith(VOID_TYPE)); // canTestForShallowEqualityWith assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(NO_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(functionType)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(recordType)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(U2U_CONSTRUCTOR_TYPE. canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(U2U_CONSTRUCTOR_TYPE.isNullable()); // isObject assertTrue(U2U_CONSTRUCTOR_TYPE.isObject()); // matchesXxx assertFalse(U2U_CONSTRUCTOR_TYPE.matchesInt32Context()); assertFalse(U2U_CONSTRUCTOR_TYPE.matchesNumberContext()); assertTrue(U2U_CONSTRUCTOR_TYPE.matchesObjectContext()); assertFalse(U2U_CONSTRUCTOR_TYPE.matchesStringContext()); assertFalse(U2U_CONSTRUCTOR_TYPE.matchesUint32Context()); // toString assertEquals("Function", U2U_CONSTRUCTOR_TYPE.toString()); assertTrue(U2U_CONSTRUCTOR_TYPE.hasDisplayName()); assertEquals("Function", U2U_CONSTRUCTOR_TYPE.getDisplayName()); // getPropertyType assertTypeEquals(UNKNOWN_TYPE, U2U_CONSTRUCTOR_TYPE.getPropertyType("anyProperty")); assertTrue(U2U_CONSTRUCTOR_TYPE.isNativeObjectType()); Asserts.assertResolvesToSame(U2U_CONSTRUCTOR_TYPE); assertTrue(U2U_CONSTRUCTOR_TYPE.isNominalConstructor()); } /** * Tests the behavior of the Bottom Object type. */ public void testNoObjectType() throws Exception { // isXxx assertTrue(NO_OBJECT_TYPE.isNoObjectType()); assertFalse(NO_OBJECT_TYPE.isNoType()); assertFalse(NO_OBJECT_TYPE.isArrayType()); assertFalse(NO_OBJECT_TYPE.isBooleanValueType()); assertFalse(NO_OBJECT_TYPE.isDateType()); assertFalse(NO_OBJECT_TYPE.isEnumElementType()); assertFalse(NO_OBJECT_TYPE.isNullType()); assertFalse(NO_OBJECT_TYPE.isNamedType()); assertFalse(NO_OBJECT_TYPE.isNullType()); assertTrue(NO_OBJECT_TYPE.isNumber()); assertFalse(NO_OBJECT_TYPE.isNumberObjectType()); assertFalse(NO_OBJECT_TYPE.isNumberValueType()); assertTrue(NO_OBJECT_TYPE.isObject()); assertFalse(NO_OBJECT_TYPE.isFunctionPrototypeType()); assertFalse(NO_OBJECT_TYPE.isRegexpType()); assertTrue(NO_OBJECT_TYPE.isString()); assertFalse(NO_OBJECT_TYPE.isStringObjectType()); assertFalse(NO_OBJECT_TYPE.isStringValueType()); assertFalse(NO_OBJECT_TYPE.isEnumType()); assertFalse(NO_OBJECT_TYPE.isUnionType()); assertFalse(NO_OBJECT_TYPE.isStruct()); assertFalse(NO_OBJECT_TYPE.isDict()); assertFalse(NO_OBJECT_TYPE.isAllType()); assertFalse(NO_OBJECT_TYPE.isVoidType()); assertTrue(NO_OBJECT_TYPE.isConstructor()); assertFalse(NO_OBJECT_TYPE.isInstanceType()); // isSubtype assertFalse(NO_OBJECT_TYPE.isSubtype(NO_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(BOOLEAN_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(DATE_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(functionType)); assertTrue(NO_OBJECT_TYPE.isSubtype(recordType)); assertFalse(NO_OBJECT_TYPE.isSubtype(NULL_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(NUMBER_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(URI_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(STRING_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(ALL_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(VOID_TYPE)); // canTestForEqualityWith assertCannotTestForEqualityWith(NO_OBJECT_TYPE, NO_TYPE); assertCannotTestForEqualityWith(NO_OBJECT_TYPE, NO_OBJECT_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, ALL_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, ARRAY_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, BOOLEAN_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, BOOLEAN_OBJECT_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, DATE_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, ERROR_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, EVAL_ERROR_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, functionType); assertCanTestForEqualityWith(NO_OBJECT_TYPE, recordType); assertCanTestForEqualityWith(NO_OBJECT_TYPE, NULL_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, NUMBER_OBJECT_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, URI_ERROR_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, RANGE_ERROR_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, REFERENCE_ERROR_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, STRING_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, SYNTAX_ERROR_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, TYPE_ERROR_TYPE); assertCanTestForEqualityWith(NO_OBJECT_TYPE, VOID_TYPE); // canTestForShallowEqualityWith assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(NO_OBJECT_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue(NO_OBJECT_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(functionType)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(recordType)); assertFalse(NO_OBJECT_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(NO_OBJECT_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertTrue(NO_OBJECT_TYPE. canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(NO_OBJECT_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertTrue(NO_OBJECT_TYPE. canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE. canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(NO_OBJECT_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(NO_OBJECT_TYPE.isNullable()); // isObject assertTrue(NO_OBJECT_TYPE.isObject()); // matchesXxx assertTrue(NO_OBJECT_TYPE.matchesInt32Context()); assertTrue(NO_OBJECT_TYPE.matchesNumberContext()); assertTrue(NO_OBJECT_TYPE.matchesObjectContext()); assertTrue(NO_OBJECT_TYPE.matchesStringContext()); assertTrue(NO_OBJECT_TYPE.matchesUint32Context()); // toString assertEquals("NoObject", NO_OBJECT_TYPE.toString()); assertFalse(NO_OBJECT_TYPE.hasDisplayName()); assertEquals(null, NO_OBJECT_TYPE.getDisplayName()); // getPropertyType assertTypeEquals(NO_TYPE, NO_OBJECT_TYPE.getPropertyType("anyProperty")); Asserts.assertResolvesToSame(NO_OBJECT_TYPE); assertFalse(NO_OBJECT_TYPE.isNominalConstructor()); } /** * Tests the behavior of the Bottom type. */ public void testNoType() throws Exception { // isXxx assertFalse(NO_TYPE.isNoObjectType()); assertTrue(NO_TYPE.isNoType()); assertFalse(NO_TYPE.isArrayType()); assertFalse(NO_TYPE.isBooleanValueType()); assertFalse(NO_TYPE.isDateType()); assertFalse(NO_TYPE.isEnumElementType()); assertFalse(NO_TYPE.isNullType()); assertFalse(NO_TYPE.isNamedType()); assertFalse(NO_TYPE.isNullType()); assertTrue(NO_TYPE.isNumber()); assertFalse(NO_TYPE.isNumberObjectType()); assertFalse(NO_TYPE.isNumberValueType()); assertTrue(NO_TYPE.isObject()); assertFalse(NO_TYPE.isFunctionPrototypeType()); assertFalse(NO_TYPE.isRegexpType()); assertTrue(NO_TYPE.isString()); assertFalse(NO_TYPE.isStringObjectType()); assertFalse(NO_TYPE.isStringValueType()); assertFalse(NO_TYPE.isEnumType()); assertFalse(NO_TYPE.isUnionType()); assertFalse(NO_TYPE.isStruct()); assertFalse(NO_TYPE.isDict()); assertFalse(NO_TYPE.isAllType()); assertFalse(NO_TYPE.isVoidType()); assertTrue(NO_TYPE.isConstructor()); assertFalse(NO_TYPE.isInstanceType()); // isSubtype assertTrue(NO_TYPE.isSubtype(NO_TYPE)); assertTrue(NO_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(ARRAY_TYPE)); assertTrue(NO_TYPE.isSubtype(BOOLEAN_TYPE)); assertTrue(NO_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(DATE_TYPE)); assertTrue(NO_TYPE.isSubtype(ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(functionType)); assertTrue(NO_TYPE.isSubtype(NULL_TYPE)); assertTrue(NO_TYPE.isSubtype(NUMBER_TYPE)); assertTrue(NO_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(URI_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(REGEXP_TYPE)); assertTrue(NO_TYPE.isSubtype(STRING_TYPE)); assertTrue(NO_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(ALL_TYPE)); assertTrue(NO_TYPE.isSubtype(VOID_TYPE)); // canTestForEqualityWith assertCannotTestForEqualityWith(NO_TYPE, NO_TYPE); assertCannotTestForEqualityWith(NO_TYPE, NO_OBJECT_TYPE); assertCanTestForEqualityWith(NO_TYPE, ARRAY_TYPE); assertCanTestForEqualityWith(NO_TYPE, BOOLEAN_TYPE); assertCanTestForEqualityWith(NO_TYPE, BOOLEAN_OBJECT_TYPE); assertCanTestForEqualityWith(NO_TYPE, DATE_TYPE); assertCanTestForEqualityWith(NO_TYPE, ERROR_TYPE); assertCanTestForEqualityWith(NO_TYPE, EVAL_ERROR_TYPE); assertCanTestForEqualityWith(NO_TYPE, functionType); assertCanTestForEqualityWith(NO_TYPE, NULL_TYPE); assertCanTestForEqualityWith(NO_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(NO_TYPE, NUMBER_OBJECT_TYPE); assertCanTestForEqualityWith(NO_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(NO_TYPE, URI_ERROR_TYPE); assertCanTestForEqualityWith(NO_TYPE, RANGE_ERROR_TYPE); assertCanTestForEqualityWith(NO_TYPE, REFERENCE_ERROR_TYPE); assertCanTestForEqualityWith(NO_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(NO_TYPE, STRING_TYPE); assertCanTestForEqualityWith(NO_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(NO_TYPE, SYNTAX_ERROR_TYPE); assertCanTestForEqualityWith(NO_TYPE, TYPE_ERROR_TYPE); assertCanTestForEqualityWith(NO_TYPE, ALL_TYPE); assertCanTestForEqualityWith(NO_TYPE, VOID_TYPE); // canTestForShallowEqualityWith assertTrue(NO_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(functionType)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertTrue(NO_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertTrue(NO_TYPE.isNullable()); // isObject assertTrue(NO_TYPE.isObject()); // matchesXxx assertTrue(NO_TYPE.matchesInt32Context()); assertTrue(NO_TYPE.matchesNumberContext()); assertTrue(NO_TYPE.matchesObjectContext()); assertTrue(NO_TYPE.matchesStringContext()); assertTrue(NO_TYPE.matchesUint32Context()); // toString assertEquals("None", NO_TYPE.toString()); assertEquals(null, NO_TYPE.getDisplayName()); assertFalse(NO_TYPE.hasDisplayName()); // getPropertyType assertTypeEquals(NO_TYPE, NO_TYPE.getPropertyType("anyProperty")); Asserts.assertResolvesToSame(NO_TYPE); assertFalse(NO_TYPE.isNominalConstructor()); } /** * Tests the behavior of the unresolved Bottom type. */ public void testNoResolvedType() throws Exception { // isXxx assertFalse(NO_RESOLVED_TYPE.isNoObjectType()); assertFalse(NO_RESOLVED_TYPE.isNoType()); assertTrue(NO_RESOLVED_TYPE.isNoResolvedType()); assertFalse(NO_RESOLVED_TYPE.isArrayType()); assertFalse(NO_RESOLVED_TYPE.isBooleanValueType()); assertFalse(NO_RESOLVED_TYPE.isDateType()); assertFalse(NO_RESOLVED_TYPE.isEnumElementType()); assertFalse(NO_RESOLVED_TYPE.isNullType()); assertFalse(NO_RESOLVED_TYPE.isNamedType()); assertTrue(NO_RESOLVED_TYPE.isNumber()); assertFalse(NO_RESOLVED_TYPE.isNumberObjectType()); assertFalse(NO_RESOLVED_TYPE.isNumberValueType()); assertTrue(NO_RESOLVED_TYPE.isObject()); assertFalse(NO_RESOLVED_TYPE.isFunctionPrototypeType()); assertFalse(NO_RESOLVED_TYPE.isRegexpType()); assertTrue(NO_RESOLVED_TYPE.isString()); assertFalse(NO_RESOLVED_TYPE.isStringObjectType()); assertFalse(NO_RESOLVED_TYPE.isStringValueType()); assertFalse(NO_RESOLVED_TYPE.isEnumType()); assertFalse(NO_RESOLVED_TYPE.isUnionType()); assertFalse(NO_RESOLVED_TYPE.isStruct()); assertFalse(NO_RESOLVED_TYPE.isDict()); assertFalse(NO_RESOLVED_TYPE.isAllType()); assertFalse(NO_RESOLVED_TYPE.isVoidType()); assertFalse(NO_RESOLVED_TYPE.isConstructor()); assertFalse(NO_RESOLVED_TYPE.isInstanceType()); // isSubtype assertTrue(NO_RESOLVED_TYPE.isSubtype(NO_RESOLVED_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(ARRAY_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(BOOLEAN_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(DATE_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(functionType)); assertTrue(NO_RESOLVED_TYPE.isSubtype(NULL_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(NUMBER_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(URI_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(REGEXP_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(STRING_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(ALL_TYPE)); assertTrue(NO_RESOLVED_TYPE.isSubtype(VOID_TYPE)); // canTestForEqualityWith assertCanTestForEqualityWith(NO_RESOLVED_TYPE, NO_RESOLVED_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, NO_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, NO_OBJECT_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, ARRAY_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, BOOLEAN_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, BOOLEAN_OBJECT_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, DATE_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, ERROR_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, EVAL_ERROR_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, functionType); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, NULL_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, NUMBER_OBJECT_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, URI_ERROR_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, RANGE_ERROR_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, REFERENCE_ERROR_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, STRING_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, SYNTAX_ERROR_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, TYPE_ERROR_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, ALL_TYPE); assertCanTestForEqualityWith(NO_RESOLVED_TYPE, VOID_TYPE); // canTestForShallowEqualityWith assertTrue( NO_RESOLVED_TYPE.canTestForShallowEqualityWith(NO_RESOLVED_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue( NO_RESOLVED_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(functionType)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertTrue( NO_RESOLVED_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertTrue( NO_RESOLVED_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertTrue( NO_RESOLVED_TYPE.canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertTrue( NO_RESOLVED_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertTrue( NO_RESOLVED_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertTrue(NO_RESOLVED_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertTrue(NO_RESOLVED_TYPE.isNullable()); // isObject assertTrue(NO_RESOLVED_TYPE.isObject()); // matchesXxx assertTrue(NO_RESOLVED_TYPE.matchesInt32Context()); assertTrue(NO_RESOLVED_TYPE.matchesNumberContext()); assertTrue(NO_RESOLVED_TYPE.matchesObjectContext()); assertTrue(NO_RESOLVED_TYPE.matchesStringContext()); assertTrue(NO_RESOLVED_TYPE.matchesUint32Context()); // toString assertEquals("NoResolvedType", NO_RESOLVED_TYPE.toString()); assertEquals(null, NO_RESOLVED_TYPE.getDisplayName()); assertFalse(NO_RESOLVED_TYPE.hasDisplayName()); // getPropertyType assertTypeEquals(CHECKED_UNKNOWN_TYPE, NO_RESOLVED_TYPE.getPropertyType("anyProperty")); Asserts.assertResolvesToSame(NO_RESOLVED_TYPE); assertTrue(forwardDeclaredNamedType.isEmptyType()); assertTrue(forwardDeclaredNamedType.isNoResolvedType()); UnionType nullable = (UnionType) registry.createNullableType(NO_RESOLVED_TYPE); assertTypeEquals( nullable, nullable.getGreatestSubtype(NULL_TYPE)); assertTypeEquals(NO_RESOLVED_TYPE, nullable.getRestrictedUnion(NULL_TYPE)); } /** * Tests the behavior of the Array type. */ public void testArrayType() throws Exception { // isXxx assertTrue(ARRAY_TYPE.isArrayType()); assertFalse(ARRAY_TYPE.isBooleanValueType()); assertFalse(ARRAY_TYPE.isDateType()); assertFalse(ARRAY_TYPE.isEnumElementType()); assertFalse(ARRAY_TYPE.isNamedType()); assertFalse(ARRAY_TYPE.isNullType()); assertFalse(ARRAY_TYPE.isNumber()); assertFalse(ARRAY_TYPE.isNumberObjectType()); assertFalse(ARRAY_TYPE.isNumberValueType()); assertTrue(ARRAY_TYPE.isObject()); assertFalse(ARRAY_TYPE.isFunctionPrototypeType()); assertTrue(ARRAY_TYPE.getImplicitPrototype().isFunctionPrototypeType()); assertFalse(ARRAY_TYPE.isRegexpType()); assertFalse(ARRAY_TYPE.isString()); assertFalse(ARRAY_TYPE.isStringObjectType()); assertFalse(ARRAY_TYPE.isStringValueType()); assertFalse(ARRAY_TYPE.isEnumType()); assertFalse(ARRAY_TYPE.isUnionType()); assertFalse(ARRAY_TYPE.isStruct()); assertFalse(ARRAY_TYPE.isDict()); assertFalse(ARRAY_TYPE.isAllType()); assertFalse(ARRAY_TYPE.isVoidType()); assertFalse(ARRAY_TYPE.isConstructor()); assertTrue(ARRAY_TYPE.isInstanceType()); // isSubtype assertFalse(ARRAY_TYPE.isSubtype(NO_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(ARRAY_TYPE.isSubtype(ALL_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(functionType)); assertFalse(ARRAY_TYPE.isSubtype(recordType)); assertFalse(ARRAY_TYPE.isSubtype(NULL_TYPE)); assertTrue(ARRAY_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(DATE_TYPE)); assertTrue(ARRAY_TYPE.isSubtype(unresolvedNamedType)); assertFalse(ARRAY_TYPE.isSubtype(namedGoogBar)); assertFalse(ARRAY_TYPE.isSubtype(REGEXP_TYPE)); // canBeCalled assertFalse(ARRAY_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(ARRAY_TYPE, NO_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, NO_OBJECT_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, ALL_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, functionType); assertCanTestForEqualityWith(ARRAY_TYPE, recordType); assertCannotTestForEqualityWith(ARRAY_TYPE, VOID_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, DATE_TYPE); assertCanTestForEqualityWith(ARRAY_TYPE, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(ARRAY_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(ARRAY_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertTrue(ARRAY_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(recordType)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(ARRAY_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(ARRAY_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(ARRAY_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(ARRAY_TYPE.isNullable()); assertTrue(createUnionType(ARRAY_TYPE, NULL_TYPE).isNullable()); // isObject assertTrue(ARRAY_TYPE.isObject()); // getLeastSupertype assertTypeEquals(ALL_TYPE, ARRAY_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(createUnionType(STRING_OBJECT_TYPE, ARRAY_TYPE), ARRAY_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(createUnionType(NUMBER_TYPE, ARRAY_TYPE), ARRAY_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(createUnionType(ARRAY_TYPE, functionType), ARRAY_TYPE.getLeastSupertype(functionType)); assertTypeEquals(OBJECT_TYPE, ARRAY_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(createUnionType(DATE_TYPE, ARRAY_TYPE), ARRAY_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(createUnionType(REGEXP_TYPE, ARRAY_TYPE), ARRAY_TYPE.getLeastSupertype(REGEXP_TYPE)); // getPropertyType assertEquals(17, ARRAY_TYPE.getImplicitPrototype().getPropertiesCount()); assertEquals(18, ARRAY_TYPE.getPropertiesCount()); assertReturnTypeEquals(ARRAY_TYPE, ARRAY_TYPE.getPropertyType("constructor")); assertReturnTypeEquals(STRING_TYPE, ARRAY_TYPE.getPropertyType("toString")); assertReturnTypeEquals(STRING_TYPE, ARRAY_TYPE.getPropertyType("toLocaleString")); assertReturnTypeEquals(ARRAY_TYPE, ARRAY_TYPE.getPropertyType("concat")); assertReturnTypeEquals(STRING_TYPE, ARRAY_TYPE.getPropertyType("join")); assertReturnTypeEquals(UNKNOWN_TYPE, ARRAY_TYPE.getPropertyType("pop")); assertReturnTypeEquals(NUMBER_TYPE, ARRAY_TYPE.getPropertyType("push")); assertReturnTypeEquals(ARRAY_TYPE, ARRAY_TYPE.getPropertyType("reverse")); assertReturnTypeEquals(UNKNOWN_TYPE, ARRAY_TYPE.getPropertyType("shift")); assertReturnTypeEquals(ARRAY_TYPE, ARRAY_TYPE.getPropertyType("slice")); assertReturnTypeEquals(ARRAY_TYPE, ARRAY_TYPE.getPropertyType("sort")); assertReturnTypeEquals(ARRAY_TYPE, ARRAY_TYPE.getPropertyType("splice")); assertReturnTypeEquals(NUMBER_TYPE, ARRAY_TYPE.getPropertyType("unshift")); assertTypeEquals(NUMBER_TYPE, ARRAY_TYPE.getPropertyType("length")); // isPropertyType* assertPropertyTypeDeclared(ARRAY_TYPE, "pop"); // matchesXxx assertFalse(ARRAY_TYPE.matchesInt32Context()); assertFalse(ARRAY_TYPE.matchesNumberContext()); assertTrue(ARRAY_TYPE.matchesObjectContext()); assertTrue(ARRAY_TYPE.matchesStringContext()); assertFalse(ARRAY_TYPE.matchesUint32Context()); // toString assertEquals("Array", ARRAY_TYPE.toString()); assertTrue(ARRAY_TYPE.hasDisplayName()); assertEquals("Array", ARRAY_TYPE.getDisplayName()); assertTrue(ARRAY_TYPE.isNativeObjectType()); Asserts.assertResolvesToSame(ARRAY_TYPE); assertFalse(ARRAY_TYPE.isNominalConstructor()); assertTrue(ARRAY_TYPE.getConstructor().isNominalConstructor()); } /** * Tests the behavior of the unknown type. */ public void testUnknownType() throws Exception { // isXxx assertFalse(UNKNOWN_TYPE.isArrayType()); assertFalse(UNKNOWN_TYPE.isBooleanObjectType()); assertFalse(UNKNOWN_TYPE.isBooleanValueType()); assertFalse(UNKNOWN_TYPE.isDateType()); assertFalse(UNKNOWN_TYPE.isEnumElementType()); assertFalse(UNKNOWN_TYPE.isNamedType()); assertFalse(UNKNOWN_TYPE.isNullType()); assertFalse(UNKNOWN_TYPE.isNumberObjectType()); assertFalse(UNKNOWN_TYPE.isNumberValueType()); assertTrue(UNKNOWN_TYPE.isObject()); assertFalse(UNKNOWN_TYPE.isFunctionPrototypeType()); assertFalse(UNKNOWN_TYPE.isRegexpType()); assertFalse(UNKNOWN_TYPE.isStringObjectType()); assertFalse(UNKNOWN_TYPE.isStringValueType()); assertFalse(UNKNOWN_TYPE.isEnumType()); assertFalse(UNKNOWN_TYPE.isUnionType()); assertFalse(UNKNOWN_TYPE.isStruct()); assertFalse(UNKNOWN_TYPE.isDict()); assertTrue(UNKNOWN_TYPE.isUnknownType()); assertFalse(UNKNOWN_TYPE.isVoidType()); assertFalse(UNKNOWN_TYPE.isConstructor()); assertFalse(UNKNOWN_TYPE.isInstanceType()); // autoboxesTo assertNull(UNKNOWN_TYPE.autoboxesTo()); // isSubtype assertTrue(UNKNOWN_TYPE.isSubtype(UNKNOWN_TYPE)); assertTrue(UNKNOWN_TYPE.isSubtype(STRING_TYPE)); assertTrue(UNKNOWN_TYPE.isSubtype(NUMBER_TYPE)); assertTrue(UNKNOWN_TYPE.isSubtype(functionType)); assertTrue(UNKNOWN_TYPE.isSubtype(recordType)); assertTrue(UNKNOWN_TYPE.isSubtype(NULL_TYPE)); assertTrue(UNKNOWN_TYPE.isSubtype(OBJECT_TYPE)); assertTrue(UNKNOWN_TYPE.isSubtype(DATE_TYPE)); assertTrue(UNKNOWN_TYPE.isSubtype(namedGoogBar)); assertTrue(UNKNOWN_TYPE.isSubtype(unresolvedNamedType)); assertTrue(UNKNOWN_TYPE.isSubtype(REGEXP_TYPE)); assertTrue(UNKNOWN_TYPE.isSubtype(VOID_TYPE)); // canBeCalled assertTrue(UNKNOWN_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(UNKNOWN_TYPE, UNKNOWN_TYPE); assertCanTestForEqualityWith(UNKNOWN_TYPE, STRING_TYPE); assertCanTestForEqualityWith(UNKNOWN_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(UNKNOWN_TYPE, functionType); assertCanTestForEqualityWith(UNKNOWN_TYPE, recordType); assertCanTestForEqualityWith(UNKNOWN_TYPE, VOID_TYPE); assertCanTestForEqualityWith(UNKNOWN_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(UNKNOWN_TYPE, DATE_TYPE); assertCanTestForEqualityWith(UNKNOWN_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(UNKNOWN_TYPE, BOOLEAN_TYPE); // canTestForShallowEqualityWith assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(UNKNOWN_TYPE)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(functionType)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(recordType)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertTrue(UNKNOWN_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); // canHaveNullValue assertTrue(UNKNOWN_TYPE.isNullable()); // getGreatestCommonType assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(UNKNOWN_TYPE)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(STRING_TYPE)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(functionType)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(REGEXP_TYPE)); // matchesXxx assertTrue(UNKNOWN_TYPE.matchesInt32Context()); assertTrue(UNKNOWN_TYPE.matchesNumberContext()); assertTrue(UNKNOWN_TYPE.matchesObjectContext()); assertTrue(UNKNOWN_TYPE.matchesStringContext()); assertTrue(UNKNOWN_TYPE.matchesUint32Context()); // isPropertyType* assertPropertyTypeUnknown(UNKNOWN_TYPE, "XXX"); // toString assertEquals("?", UNKNOWN_TYPE.toString()); assertTrue(UNKNOWN_TYPE.hasDisplayName()); assertEquals("Unknown", UNKNOWN_TYPE.getDisplayName()); Asserts.assertResolvesToSame(UNKNOWN_TYPE); assertFalse(UNKNOWN_TYPE.isNominalConstructor()); assertEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getPropertyType("abc")); } /** * Tests the behavior of the checked unknown type. */ public void testCheckedUnknownType() throws Exception { // isPropertyType* assertPropertyTypeUnknown(CHECKED_UNKNOWN_TYPE, "XXX"); // toString assertEquals("??", CHECKED_UNKNOWN_TYPE.toString()); assertTrue(CHECKED_UNKNOWN_TYPE.hasDisplayName()); assertEquals("Unknown", CHECKED_UNKNOWN_TYPE.getDisplayName()); Asserts.assertResolvesToSame(CHECKED_UNKNOWN_TYPE); assertFalse(CHECKED_UNKNOWN_TYPE.isNominalConstructor()); assertEquals(CHECKED_UNKNOWN_TYPE, CHECKED_UNKNOWN_TYPE.getPropertyType("abc")); } /** * Tests the behavior of the unknown type. */ public void testAllType() throws Exception { // isXxx assertFalse(ALL_TYPE.isArrayType()); assertFalse(ALL_TYPE.isBooleanValueType()); assertFalse(ALL_TYPE.isDateType()); assertFalse(ALL_TYPE.isEnumElementType()); assertFalse(ALL_TYPE.isNamedType()); assertFalse(ALL_TYPE.isNullType()); assertFalse(ALL_TYPE.isNumber()); assertFalse(ALL_TYPE.isNumberObjectType()); assertFalse(ALL_TYPE.isNumberValueType()); assertFalse(ALL_TYPE.isObject()); assertFalse(ALL_TYPE.isFunctionPrototypeType()); assertFalse(ALL_TYPE.isRegexpType()); assertFalse(ALL_TYPE.isString()); assertFalse(ALL_TYPE.isStringObjectType()); assertFalse(ALL_TYPE.isStringValueType()); assertFalse(ALL_TYPE.isEnumType()); assertFalse(ALL_TYPE.isUnionType()); assertFalse(ALL_TYPE.isStruct()); assertFalse(ALL_TYPE.isDict()); assertTrue(ALL_TYPE.isAllType()); assertFalse(ALL_TYPE.isVoidType()); assertFalse(ALL_TYPE.isConstructor()); assertFalse(ALL_TYPE.isInstanceType()); // isSubtype assertFalse(ALL_TYPE.isSubtype(NO_TYPE)); assertFalse(ALL_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(ALL_TYPE.isSubtype(ALL_TYPE)); assertFalse(ALL_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(ALL_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(ALL_TYPE.isSubtype(functionType)); assertFalse(ALL_TYPE.isSubtype(recordType)); assertFalse(ALL_TYPE.isSubtype(NULL_TYPE)); assertFalse(ALL_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(ALL_TYPE.isSubtype(DATE_TYPE)); assertTrue(ALL_TYPE.isSubtype(unresolvedNamedType)); assertFalse(ALL_TYPE.isSubtype(namedGoogBar)); assertFalse(ALL_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(ALL_TYPE.isSubtype(VOID_TYPE)); assertTrue(ALL_TYPE.isSubtype(UNKNOWN_TYPE)); // canBeCalled assertFalse(ALL_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(ALL_TYPE, ALL_TYPE); assertCanTestForEqualityWith(ALL_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(ALL_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(ALL_TYPE, functionType); assertCanTestForEqualityWith(ALL_TYPE, recordType); assertCanTestForEqualityWith(ALL_TYPE, VOID_TYPE); assertCanTestForEqualityWith(ALL_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(ALL_TYPE, DATE_TYPE); assertCanTestForEqualityWith(ALL_TYPE, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(ALL_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(functionType)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(recordType)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertTrue(ALL_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(ALL_TYPE.isNullable()); // getLeastSupertype assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(UNKNOWN_TYPE)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(functionType)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getLeastSupertype(REGEXP_TYPE)); // matchesXxx assertFalse(ALL_TYPE.matchesInt32Context()); assertFalse(ALL_TYPE.matchesNumberContext()); assertTrue(ALL_TYPE.matchesObjectContext()); assertTrue(ALL_TYPE.matchesStringContext()); assertFalse(ALL_TYPE.matchesUint32Context()); // toString assertEquals("*", ALL_TYPE.toString()); assertTrue(ALL_TYPE.hasDisplayName()); assertEquals("<Any Type>", ALL_TYPE.getDisplayName()); Asserts.assertResolvesToSame(ALL_TYPE); assertFalse(ALL_TYPE.isNominalConstructor()); } /** * Tests the behavior of the Object type (the object * at the top of the JavaScript hierarchy). */ public void testTheObjectType() throws Exception { // implicit prototype assertTypeEquals(OBJECT_PROTOTYPE, OBJECT_TYPE.getImplicitPrototype()); // isXxx assertFalse(OBJECT_TYPE.isNoObjectType()); assertFalse(OBJECT_TYPE.isNoType()); assertFalse(OBJECT_TYPE.isArrayType()); assertFalse(OBJECT_TYPE.isBooleanValueType()); assertFalse(OBJECT_TYPE.isDateType()); assertFalse(OBJECT_TYPE.isEnumElementType()); assertFalse(OBJECT_TYPE.isNullType()); assertFalse(OBJECT_TYPE.isNamedType()); assertFalse(OBJECT_TYPE.isNullType()); assertFalse(OBJECT_TYPE.isNumber()); assertFalse(OBJECT_TYPE.isNumberObjectType()); assertFalse(OBJECT_TYPE.isNumberValueType()); assertTrue(OBJECT_TYPE.isObject()); assertFalse(OBJECT_TYPE.isFunctionPrototypeType()); assertTrue(OBJECT_TYPE.getImplicitPrototype().isFunctionPrototypeType()); assertFalse(OBJECT_TYPE.isRegexpType()); assertFalse(OBJECT_TYPE.isString()); assertFalse(OBJECT_TYPE.isStringObjectType()); assertFalse(OBJECT_TYPE.isStringValueType()); assertFalse(OBJECT_TYPE.isEnumType()); assertFalse(OBJECT_TYPE.isUnionType()); assertFalse(OBJECT_TYPE.isStruct()); assertFalse(OBJECT_TYPE.isDict()); assertFalse(OBJECT_TYPE.isAllType()); assertFalse(OBJECT_TYPE.isVoidType()); assertFalse(OBJECT_TYPE.isConstructor()); assertTrue(OBJECT_TYPE.isInstanceType()); // isSubtype assertFalse(OBJECT_TYPE.isSubtype(NO_TYPE)); assertTrue(OBJECT_TYPE.isSubtype(ALL_TYPE)); assertFalse(OBJECT_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(OBJECT_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(OBJECT_TYPE.isSubtype(functionType)); assertFalse(OBJECT_TYPE.isSubtype(recordType)); assertFalse(OBJECT_TYPE.isSubtype(NULL_TYPE)); assertTrue(OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(OBJECT_TYPE.isSubtype(DATE_TYPE)); assertFalse(OBJECT_TYPE.isSubtype(namedGoogBar)); assertTrue(OBJECT_TYPE.isSubtype(unresolvedNamedType)); assertFalse(OBJECT_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(OBJECT_TYPE.isSubtype(ARRAY_TYPE)); assertTrue(OBJECT_TYPE.isSubtype(UNKNOWN_TYPE)); // canBeCalled assertFalse(OBJECT_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(OBJECT_TYPE, ALL_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, STRING_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, BOOLEAN_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, functionType); assertCanTestForEqualityWith(OBJECT_TYPE, recordType); assertCannotTestForEqualityWith(OBJECT_TYPE, VOID_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, DATE_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, ARRAY_TYPE); assertCanTestForEqualityWith(OBJECT_TYPE, UNKNOWN_TYPE); // canTestForShallowEqualityWith assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(OBJECT_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(functionType)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(recordType)); assertFalse(OBJECT_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(OBJECT_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertTrue(OBJECT_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(OBJECT_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(OBJECT_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(OBJECT_TYPE.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // isNullable assertFalse(OBJECT_TYPE.isNullable()); // getLeastSupertype assertTypeEquals(ALL_TYPE, OBJECT_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(OBJECT_TYPE, OBJECT_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(createUnionType(OBJECT_TYPE, NUMBER_TYPE), OBJECT_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(OBJECT_TYPE, OBJECT_TYPE.getLeastSupertype(functionType)); assertTypeEquals(OBJECT_TYPE, OBJECT_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(OBJECT_TYPE, OBJECT_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(OBJECT_TYPE, OBJECT_TYPE.getLeastSupertype(REGEXP_TYPE)); // getPropertyType assertEquals(7, OBJECT_TYPE.getPropertiesCount()); assertReturnTypeEquals(OBJECT_TYPE, OBJECT_TYPE.getPropertyType("constructor")); assertReturnTypeEquals(STRING_TYPE, OBJECT_TYPE.getPropertyType("toString")); assertReturnTypeEquals(STRING_TYPE, OBJECT_TYPE.getPropertyType("toLocaleString")); assertReturnTypeEquals(UNKNOWN_TYPE, OBJECT_TYPE.getPropertyType("valueOf")); assertReturnTypeEquals(BOOLEAN_TYPE, OBJECT_TYPE.getPropertyType("hasOwnProperty")); assertReturnTypeEquals(BOOLEAN_TYPE, OBJECT_TYPE.getPropertyType("isPrototypeOf")); assertReturnTypeEquals(BOOLEAN_TYPE, OBJECT_TYPE.getPropertyType("propertyIsEnumerable")); // matchesXxx assertFalse(OBJECT_TYPE.matchesInt32Context()); assertFalse(OBJECT_TYPE.matchesNumberContext()); assertTrue(OBJECT_TYPE.matchesObjectContext()); assertTrue(OBJECT_TYPE.matchesStringContext()); assertFalse(OBJECT_TYPE.matchesUint32Context()); // implicit prototype assertTypeEquals(OBJECT_PROTOTYPE, OBJECT_TYPE.getImplicitPrototype()); // toString assertEquals("Object", OBJECT_TYPE.toString()); assertTrue(OBJECT_TYPE.isNativeObjectType()); assertTrue(OBJECT_TYPE.getImplicitPrototype().isNativeObjectType()); Asserts.assertResolvesToSame(OBJECT_TYPE); assertFalse(OBJECT_TYPE.isNominalConstructor()); assertTrue(OBJECT_TYPE.getConstructor().isNominalConstructor()); } /** * Tests the behavior of the number value type. */ public void testNumberObjectType() throws Exception { // isXxx assertFalse(NUMBER_OBJECT_TYPE.isArrayType()); assertFalse(NUMBER_OBJECT_TYPE.isBooleanObjectType()); assertFalse(NUMBER_OBJECT_TYPE.isBooleanValueType()); assertFalse(NUMBER_OBJECT_TYPE.isDateType()); assertFalse(NUMBER_OBJECT_TYPE.isEnumElementType()); assertFalse(NUMBER_OBJECT_TYPE.isNamedType()); assertFalse(NUMBER_OBJECT_TYPE.isNullType()); assertTrue(NUMBER_OBJECT_TYPE.isNumber()); assertTrue(NUMBER_OBJECT_TYPE.isNumberObjectType()); assertFalse(NUMBER_OBJECT_TYPE.isNumberValueType()); assertTrue(NUMBER_OBJECT_TYPE.isObject()); assertFalse(NUMBER_OBJECT_TYPE.isFunctionPrototypeType()); assertTrue( NUMBER_OBJECT_TYPE.getImplicitPrototype().isFunctionPrototypeType()); assertFalse(NUMBER_OBJECT_TYPE.isRegexpType()); assertFalse(NUMBER_OBJECT_TYPE.isString()); assertFalse(NUMBER_OBJECT_TYPE.isStringObjectType()); assertFalse(NUMBER_OBJECT_TYPE.isStringValueType()); assertFalse(NUMBER_OBJECT_TYPE.isEnumType()); assertFalse(NUMBER_OBJECT_TYPE.isUnionType()); assertFalse(NUMBER_OBJECT_TYPE.isStruct()); assertFalse(NUMBER_OBJECT_TYPE.isDict()); assertFalse(NUMBER_OBJECT_TYPE.isAllType()); assertFalse(NUMBER_OBJECT_TYPE.isVoidType()); assertFalse(NUMBER_OBJECT_TYPE.isConstructor()); assertTrue(NUMBER_OBJECT_TYPE.isInstanceType()); // autoboxesTo assertTypeEquals(NUMBER_OBJECT_TYPE, NUMBER_TYPE.autoboxesTo()); // unboxesTo assertTypeEquals(NUMBER_TYPE, NUMBER_OBJECT_TYPE.unboxesTo()); // isSubtype assertTrue(NUMBER_OBJECT_TYPE.isSubtype(ALL_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.isSubtype(functionType)); assertFalse(NUMBER_OBJECT_TYPE.isSubtype(NULL_TYPE)); assertTrue(NUMBER_OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.isSubtype(DATE_TYPE)); assertTrue(NUMBER_OBJECT_TYPE.isSubtype(unresolvedNamedType)); assertFalse(NUMBER_OBJECT_TYPE.isSubtype(namedGoogBar)); assertTrue(NUMBER_OBJECT_TYPE.isSubtype( createUnionType(NUMBER_OBJECT_TYPE, NULL_TYPE))); assertFalse(NUMBER_OBJECT_TYPE.isSubtype( createUnionType(NUMBER_TYPE, NULL_TYPE))); assertTrue(NUMBER_OBJECT_TYPE.isSubtype(UNKNOWN_TYPE)); // canBeCalled assertFalse(NUMBER_OBJECT_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, NO_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, NO_OBJECT_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, ALL_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, functionType); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, elementsType); assertCannotTestForEqualityWith(NUMBER_OBJECT_TYPE, VOID_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, DATE_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(NUMBER_OBJECT_TYPE, ARRAY_TYPE); // canTestForShallowEqualityWith assertTrue(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertTrue(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(NUMBER_OBJECT_TYPE. canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(NUMBER_OBJECT_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(NUMBER_OBJECT_TYPE.isNullable()); // getLeastSupertype assertTypeEquals(ALL_TYPE, NUMBER_OBJECT_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(createUnionType(NUMBER_OBJECT_TYPE, STRING_OBJECT_TYPE), NUMBER_OBJECT_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(createUnionType(NUMBER_OBJECT_TYPE, NUMBER_TYPE), NUMBER_OBJECT_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(createUnionType(NUMBER_OBJECT_TYPE, functionType), NUMBER_OBJECT_TYPE.getLeastSupertype(functionType)); assertTypeEquals(OBJECT_TYPE, NUMBER_OBJECT_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(createUnionType(NUMBER_OBJECT_TYPE, DATE_TYPE), NUMBER_OBJECT_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(createUnionType(NUMBER_OBJECT_TYPE, REGEXP_TYPE), NUMBER_OBJECT_TYPE.getLeastSupertype(REGEXP_TYPE)); // matchesXxx assertTrue(NUMBER_OBJECT_TYPE.matchesInt32Context()); assertTrue(NUMBER_OBJECT_TYPE.matchesNumberContext()); assertTrue(NUMBER_OBJECT_TYPE.matchesObjectContext()); assertTrue(NUMBER_OBJECT_TYPE.matchesStringContext()); assertTrue(NUMBER_OBJECT_TYPE.matchesUint32Context()); // toString assertEquals("Number", NUMBER_OBJECT_TYPE.toString()); assertTrue(NUMBER_OBJECT_TYPE.hasDisplayName()); assertEquals("Number", NUMBER_OBJECT_TYPE.getDisplayName()); assertTrue(NUMBER_OBJECT_TYPE.isNativeObjectType()); Asserts.assertResolvesToSame(NUMBER_OBJECT_TYPE); } /** * Tests the behavior of the number value type. */ public void testNumberValueType() throws Exception { // isXxx assertFalse(NUMBER_TYPE.isArrayType()); assertFalse(NUMBER_TYPE.isBooleanObjectType()); assertFalse(NUMBER_TYPE.isBooleanValueType()); assertFalse(NUMBER_TYPE.isDateType()); assertFalse(NUMBER_TYPE.isEnumElementType()); assertFalse(NUMBER_TYPE.isNamedType()); assertFalse(NUMBER_TYPE.isNullType()); assertTrue(NUMBER_TYPE.isNumber()); assertFalse(NUMBER_TYPE.isNumberObjectType()); assertTrue(NUMBER_TYPE.isNumberValueType()); assertFalse(NUMBER_TYPE.isFunctionPrototypeType()); assertFalse(NUMBER_TYPE.isRegexpType()); assertFalse(NUMBER_TYPE.isString()); assertFalse(NUMBER_TYPE.isStringObjectType()); assertFalse(NUMBER_TYPE.isStringValueType()); assertFalse(NUMBER_TYPE.isEnumType()); assertFalse(NUMBER_TYPE.isUnionType()); assertFalse(NUMBER_TYPE.isStruct()); assertFalse(NUMBER_TYPE.isDict()); assertFalse(NUMBER_TYPE.isAllType()); assertFalse(NUMBER_TYPE.isVoidType()); assertFalse(NUMBER_TYPE.isConstructor()); assertFalse(NUMBER_TYPE.isInstanceType()); // autoboxesTo assertTypeEquals(NUMBER_OBJECT_TYPE, NUMBER_TYPE.autoboxesTo()); // isSubtype assertTrue(NUMBER_TYPE.isSubtype(ALL_TYPE)); assertFalse(NUMBER_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertTrue(NUMBER_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(NUMBER_TYPE.isSubtype(functionType)); assertFalse(NUMBER_TYPE.isSubtype(NULL_TYPE)); assertFalse(NUMBER_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(NUMBER_TYPE.isSubtype(DATE_TYPE)); assertTrue(NUMBER_TYPE.isSubtype(unresolvedNamedType)); assertFalse(NUMBER_TYPE.isSubtype(namedGoogBar)); assertTrue(NUMBER_TYPE.isSubtype( createUnionType(NUMBER_TYPE, NULL_TYPE))); assertTrue(NUMBER_TYPE.isSubtype(UNKNOWN_TYPE)); // canBeCalled assertFalse(NUMBER_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(NUMBER_TYPE, NO_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, NO_OBJECT_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, ALL_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, STRING_OBJECT_TYPE); assertCannotTestForEqualityWith(NUMBER_TYPE, functionType); assertCannotTestForEqualityWith(NUMBER_TYPE, VOID_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, DATE_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, ARRAY_TYPE); assertCanTestForEqualityWith(NUMBER_TYPE, UNKNOWN_TYPE); // canTestForShallowEqualityWith assertTrue(NUMBER_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertTrue(NUMBER_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(NUMBER_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(NUMBER_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(NUMBER_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(NUMBER_TYPE.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // isNullable assertFalse(NUMBER_TYPE.isNullable()); // getLeastSupertype assertTypeEquals(ALL_TYPE, NUMBER_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(createUnionType(NUMBER_TYPE, STRING_OBJECT_TYPE), NUMBER_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(NUMBER_TYPE, NUMBER_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(createUnionType(NUMBER_TYPE, functionType), NUMBER_TYPE.getLeastSupertype(functionType)); assertTypeEquals(createUnionType(NUMBER_TYPE, OBJECT_TYPE), NUMBER_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(createUnionType(NUMBER_TYPE, DATE_TYPE), NUMBER_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(createUnionType(NUMBER_TYPE, REGEXP_TYPE), NUMBER_TYPE.getLeastSupertype(REGEXP_TYPE)); // matchesXxx assertTrue(NUMBER_TYPE.matchesInt32Context()); assertTrue(NUMBER_TYPE.matchesNumberContext()); assertTrue(NUMBER_TYPE.matchesObjectContext()); assertTrue(NUMBER_TYPE.matchesStringContext()); assertTrue(NUMBER_TYPE.matchesUint32Context()); // toString assertEquals("number", NUMBER_TYPE.toString()); assertTrue(NUMBER_TYPE.hasDisplayName()); assertEquals("number", NUMBER_TYPE.getDisplayName()); Asserts.assertResolvesToSame(NUMBER_TYPE); assertFalse(NUMBER_TYPE.isNominalConstructor()); } /** * Tests the behavior of the null type. */ public void testNullType() throws Exception { // isXxx assertFalse(NULL_TYPE.isArrayType()); assertFalse(NULL_TYPE.isBooleanValueType()); assertFalse(NULL_TYPE.isDateType()); assertFalse(NULL_TYPE.isEnumElementType()); assertFalse(NULL_TYPE.isNamedType()); assertTrue(NULL_TYPE.isNullType()); assertFalse(NULL_TYPE.isNumber()); assertFalse(NULL_TYPE.isNumberObjectType()); assertFalse(NULL_TYPE.isNumberValueType()); assertFalse(NULL_TYPE.isFunctionPrototypeType()); assertFalse(NULL_TYPE.isRegexpType()); assertFalse(NULL_TYPE.isString()); assertFalse(NULL_TYPE.isStringObjectType()); assertFalse(NULL_TYPE.isStringValueType()); assertFalse(NULL_TYPE.isEnumType()); assertFalse(NULL_TYPE.isUnionType()); assertFalse(NULL_TYPE.isStruct()); assertFalse(NULL_TYPE.isDict()); assertFalse(NULL_TYPE.isAllType()); assertFalse(NULL_TYPE.isVoidType()); assertFalse(NULL_TYPE.isConstructor()); assertFalse(NULL_TYPE.isInstanceType()); // autoboxesTo assertNull(NULL_TYPE.autoboxesTo()); // isSubtype assertFalse(NULL_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(NULL_TYPE.isSubtype(NO_TYPE)); assertTrue(NULL_TYPE.isSubtype(NULL_TYPE)); assertTrue(NULL_TYPE.isSubtype(ALL_TYPE)); assertFalse(NULL_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(NULL_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(NULL_TYPE.isSubtype(functionType)); assertFalse(NULL_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(NULL_TYPE.isSubtype(DATE_TYPE)); assertFalse(NULL_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(NULL_TYPE.isSubtype(ARRAY_TYPE)); assertTrue(NULL_TYPE.isSubtype(UNKNOWN_TYPE)); assertTrue(NULL_TYPE.isSubtype(createNullableType(NO_OBJECT_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(NO_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(NULL_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(ALL_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(STRING_OBJECT_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(NUMBER_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(functionType))); assertTrue(NULL_TYPE.isSubtype(createNullableType(OBJECT_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(DATE_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(REGEXP_TYPE))); assertTrue(NULL_TYPE.isSubtype(createNullableType(ARRAY_TYPE))); // canBeCalled assertFalse(NULL_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(NULL_TYPE, NO_TYPE); assertCanTestForEqualityWith(NULL_TYPE, NO_OBJECT_TYPE); assertCanTestForEqualityWith(NULL_TYPE, ALL_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, ARRAY_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, BOOLEAN_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, BOOLEAN_OBJECT_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, DATE_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, ERROR_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, EVAL_ERROR_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, functionType); assertCannotTestForEqualityWith(NULL_TYPE, NULL_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, NUMBER_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, NUMBER_OBJECT_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, OBJECT_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, URI_ERROR_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, RANGE_ERROR_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, REFERENCE_ERROR_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, REGEXP_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, STRING_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, STRING_OBJECT_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, SYNTAX_ERROR_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, TYPE_ERROR_TYPE); assertCannotTestForEqualityWith(NULL_TYPE, VOID_TYPE); // canTestForShallowEqualityWith assertTrue(NULL_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(NULL_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(functionType)); assertTrue(NULL_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(NULL_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(NULL_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(NULL_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(NULL_TYPE.canTestForShallowEqualityWith( createNullableType(STRING_OBJECT_TYPE))); // getLeastSupertype assertTypeEquals(NULL_TYPE, NULL_TYPE.getLeastSupertype(NULL_TYPE)); assertTypeEquals(ALL_TYPE, NULL_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(createNullableType(STRING_OBJECT_TYPE), NULL_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(createNullableType(NUMBER_TYPE), NULL_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(createNullableType(functionType), NULL_TYPE.getLeastSupertype(functionType)); assertTypeEquals(createNullableType(OBJECT_TYPE), NULL_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(createNullableType(DATE_TYPE), NULL_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(createNullableType(REGEXP_TYPE), NULL_TYPE.getLeastSupertype(REGEXP_TYPE)); // matchesXxx assertTrue(NULL_TYPE.matchesInt32Context()); assertTrue(NULL_TYPE.matchesNumberContext()); assertFalse(NULL_TYPE.matchesObjectContext()); assertTrue(NULL_TYPE.matchesStringContext()); assertTrue(NULL_TYPE.matchesUint32Context()); // matchesObjectContext assertFalse(NULL_TYPE.matchesObjectContext()); // toString assertEquals("null", NULL_TYPE.toString()); assertTrue(NULL_TYPE.hasDisplayName()); assertEquals("null", NULL_TYPE.getDisplayName()); Asserts.assertResolvesToSame(NULL_TYPE); // getGreatestSubtype assertTrue( NULL_TYPE.isSubtype( createUnionType(forwardDeclaredNamedType, NULL_TYPE))); assertTypeEquals( createUnionType(forwardDeclaredNamedType, NULL_TYPE), NULL_TYPE.getGreatestSubtype( createUnionType(forwardDeclaredNamedType, NULL_TYPE))); assertFalse(NULL_TYPE.isNominalConstructor()); assertTrue(NULL_TYPE.differsFrom(UNKNOWN_TYPE)); } /** * Tests the behavior of the Date type. */ public void testDateType() throws Exception { // isXxx assertFalse(DATE_TYPE.isArrayType()); assertFalse(DATE_TYPE.isBooleanValueType()); assertTrue(DATE_TYPE.isDateType()); assertFalse(DATE_TYPE.isEnumElementType()); assertFalse(DATE_TYPE.isNamedType()); assertFalse(DATE_TYPE.isNullType()); assertFalse(DATE_TYPE.isNumberValueType()); assertFalse(DATE_TYPE.isFunctionPrototypeType()); assertTrue(DATE_TYPE.getImplicitPrototype().isFunctionPrototypeType()); assertFalse(DATE_TYPE.isRegexpType()); assertFalse(DATE_TYPE.isStringValueType()); assertFalse(DATE_TYPE.isEnumType()); assertFalse(DATE_TYPE.isUnionType()); assertFalse(DATE_TYPE.isStruct()); assertFalse(DATE_TYPE.isDict()); assertFalse(DATE_TYPE.isAllType()); assertFalse(DATE_TYPE.isVoidType()); assertFalse(DATE_TYPE.isConstructor()); assertTrue(DATE_TYPE.isInstanceType()); // autoboxesTo assertNull(DATE_TYPE.autoboxesTo()); // isSubtype assertFalse(DATE_TYPE.isSubtype(NO_TYPE)); assertFalse(DATE_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(DATE_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(DATE_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(DATE_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertTrue(DATE_TYPE.isSubtype(DATE_TYPE)); assertFalse(DATE_TYPE.isSubtype(ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(functionType)); assertFalse(DATE_TYPE.isSubtype(NULL_TYPE)); assertFalse(DATE_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(DATE_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(DATE_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(DATE_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(DATE_TYPE.isSubtype(STRING_TYPE)); assertFalse(DATE_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(DATE_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(DATE_TYPE.isSubtype(ALL_TYPE)); assertFalse(DATE_TYPE.isSubtype(VOID_TYPE)); // canBeCalled assertFalse(DATE_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(DATE_TYPE, ALL_TYPE); assertCanTestForEqualityWith(DATE_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(DATE_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(DATE_TYPE, functionType); assertCannotTestForEqualityWith(DATE_TYPE, VOID_TYPE); assertCanTestForEqualityWith(DATE_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(DATE_TYPE, DATE_TYPE); assertCanTestForEqualityWith(DATE_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(DATE_TYPE, ARRAY_TYPE); // canTestForShallowEqualityWith assertTrue(DATE_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(DATE_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(DATE_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertTrue(DATE_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(DATE_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(DATE_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(DATE_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(DATE_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(DATE_TYPE.isNullable()); assertTrue(createNullableType(DATE_TYPE).isNullable()); // getLeastSupertype assertTypeEquals(ALL_TYPE, DATE_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(createUnionType(DATE_TYPE, STRING_OBJECT_TYPE), DATE_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(createUnionType(DATE_TYPE, NUMBER_TYPE), DATE_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(createUnionType(DATE_TYPE, functionType), DATE_TYPE.getLeastSupertype(functionType)); assertTypeEquals(OBJECT_TYPE, DATE_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(DATE_TYPE, DATE_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(createUnionType(DATE_TYPE, REGEXP_TYPE), DATE_TYPE.getLeastSupertype(REGEXP_TYPE)); // getPropertyType assertEquals(46, DATE_TYPE.getImplicitPrototype().getPropertiesCount()); assertEquals(46, DATE_TYPE.getPropertiesCount()); assertReturnTypeEquals(DATE_TYPE, DATE_TYPE.getPropertyType("constructor")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toString")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toDateString")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toTimeString")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toLocaleString")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toLocaleDateString")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toLocaleTimeString")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("valueOf")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getTime")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getFullYear")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCFullYear")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getMonth")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCMonth")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getDate")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCDate")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getDay")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCDay")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getHours")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCHours")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getMinutes")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCMinutes")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getSeconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCSeconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getMilliseconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getUTCMilliseconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("getTimezoneOffset")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setTime")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setMilliseconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCMilliseconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setSeconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCSeconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCSeconds")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setMinutes")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCMinutes")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setHours")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCHours")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setDate")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCDate")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setMonth")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCMonth")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setFullYear")); assertReturnTypeEquals(NUMBER_TYPE, DATE_TYPE.getPropertyType("setUTCFullYear")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toUTCString")); assertReturnTypeEquals(STRING_TYPE, DATE_TYPE.getPropertyType("toGMTString")); // matchesXxx assertTrue(DATE_TYPE.matchesInt32Context()); assertTrue(DATE_TYPE.matchesNumberContext()); assertTrue(DATE_TYPE.matchesObjectContext()); assertTrue(DATE_TYPE.matchesStringContext()); assertTrue(DATE_TYPE.matchesUint32Context()); // toString assertEquals("Date", DATE_TYPE.toString()); assertTrue(DATE_TYPE.hasDisplayName()); assertEquals("Date", DATE_TYPE.getDisplayName()); assertTrue(DATE_TYPE.isNativeObjectType()); Asserts.assertResolvesToSame(DATE_TYPE); assertFalse(DATE_TYPE.isNominalConstructor()); assertTrue(DATE_TYPE.getConstructor().isNominalConstructor()); } /** * Tests the behavior of the RegExp type. */ public void testRegExpType() throws Exception { // isXxx assertFalse(REGEXP_TYPE.isNoType()); assertFalse(REGEXP_TYPE.isNoObjectType()); assertFalse(REGEXP_TYPE.isArrayType()); assertFalse(REGEXP_TYPE.isBooleanValueType()); assertFalse(REGEXP_TYPE.isDateType()); assertFalse(REGEXP_TYPE.isEnumElementType()); assertFalse(REGEXP_TYPE.isNamedType()); assertFalse(REGEXP_TYPE.isNullType()); assertFalse(REGEXP_TYPE.isNumberValueType()); assertFalse(REGEXP_TYPE.isFunctionPrototypeType()); assertTrue(REGEXP_TYPE.getImplicitPrototype().isFunctionPrototypeType()); assertTrue(REGEXP_TYPE.isRegexpType()); assertFalse(REGEXP_TYPE.isStringValueType()); assertFalse(REGEXP_TYPE.isEnumType()); assertFalse(REGEXP_TYPE.isUnionType()); assertFalse(REGEXP_TYPE.isStruct()); assertFalse(REGEXP_TYPE.isDict()); assertFalse(REGEXP_TYPE.isAllType()); assertFalse(REGEXP_TYPE.isVoidType()); // autoboxesTo assertNull(REGEXP_TYPE.autoboxesTo()); // isSubtype assertFalse(REGEXP_TYPE.isSubtype(NO_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(DATE_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(ERROR_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(functionType)); assertFalse(REGEXP_TYPE.isSubtype(NULL_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(REGEXP_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertTrue(REGEXP_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(STRING_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(REGEXP_TYPE.isSubtype(ALL_TYPE)); assertFalse(REGEXP_TYPE.isSubtype(VOID_TYPE)); // canBeCalled assertTrue(REGEXP_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(REGEXP_TYPE, ALL_TYPE); assertCanTestForEqualityWith(REGEXP_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(REGEXP_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(REGEXP_TYPE, functionType); assertCannotTestForEqualityWith(REGEXP_TYPE, VOID_TYPE); assertCanTestForEqualityWith(REGEXP_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(REGEXP_TYPE, DATE_TYPE); assertCanTestForEqualityWith(REGEXP_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(REGEXP_TYPE, ARRAY_TYPE); // canTestForShallowEqualityWith assertTrue(REGEXP_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(REGEXP_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(REGEXP_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(REGEXP_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(REGEXP_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertTrue(REGEXP_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(REGEXP_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(REGEXP_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(REGEXP_TYPE.isNullable()); assertTrue(createNullableType(REGEXP_TYPE).isNullable()); // getLeastSupertype assertTypeEquals(ALL_TYPE, REGEXP_TYPE.getLeastSupertype(ALL_TYPE)); assertTypeEquals(createUnionType(REGEXP_TYPE, STRING_OBJECT_TYPE), REGEXP_TYPE.getLeastSupertype(STRING_OBJECT_TYPE)); assertTypeEquals(createUnionType(REGEXP_TYPE, NUMBER_TYPE), REGEXP_TYPE.getLeastSupertype(NUMBER_TYPE)); assertTypeEquals(createUnionType(REGEXP_TYPE, functionType), REGEXP_TYPE.getLeastSupertype(functionType)); assertTypeEquals(OBJECT_TYPE, REGEXP_TYPE.getLeastSupertype(OBJECT_TYPE)); assertTypeEquals(createUnionType(DATE_TYPE, REGEXP_TYPE), REGEXP_TYPE.getLeastSupertype(DATE_TYPE)); assertTypeEquals(REGEXP_TYPE, REGEXP_TYPE.getLeastSupertype(REGEXP_TYPE)); // getPropertyType assertEquals(9, REGEXP_TYPE.getImplicitPrototype().getPropertiesCount()); assertEquals(14, REGEXP_TYPE.getPropertiesCount()); assertReturnTypeEquals(REGEXP_TYPE, REGEXP_TYPE.getPropertyType("constructor")); assertReturnTypeEquals(createNullableType(ARRAY_TYPE), REGEXP_TYPE.getPropertyType("exec")); assertReturnTypeEquals(BOOLEAN_TYPE, REGEXP_TYPE.getPropertyType("test")); assertReturnTypeEquals(STRING_TYPE, REGEXP_TYPE.getPropertyType("toString")); assertTypeEquals(STRING_TYPE, REGEXP_TYPE.getPropertyType("source")); assertTypeEquals(BOOLEAN_TYPE, REGEXP_TYPE.getPropertyType("global")); assertTypeEquals(BOOLEAN_TYPE, REGEXP_TYPE.getPropertyType("ignoreCase")); assertTypeEquals(BOOLEAN_TYPE, REGEXP_TYPE.getPropertyType("multiline")); assertTypeEquals(NUMBER_TYPE, REGEXP_TYPE.getPropertyType("lastIndex")); // matchesXxx assertFalse(REGEXP_TYPE.matchesInt32Context()); assertFalse(REGEXP_TYPE.matchesNumberContext()); assertTrue(REGEXP_TYPE.matchesObjectContext()); assertTrue(REGEXP_TYPE.matchesStringContext()); assertFalse(REGEXP_TYPE.matchesUint32Context()); // toString assertEquals("RegExp", REGEXP_TYPE.toString()); assertTrue(REGEXP_TYPE.hasDisplayName()); assertEquals("RegExp", REGEXP_TYPE.getDisplayName()); assertTrue(REGEXP_TYPE.isNativeObjectType()); Asserts.assertResolvesToSame(REGEXP_TYPE); assertFalse(REGEXP_TYPE.isNominalConstructor()); assertTrue(REGEXP_TYPE.getConstructor().isNominalConstructor()); } /** * Tests the behavior of the string object type. */ public void testStringObjectType() throws Exception { // isXxx assertFalse(STRING_OBJECT_TYPE.isArrayType()); assertFalse(STRING_OBJECT_TYPE.isBooleanObjectType()); assertFalse(STRING_OBJECT_TYPE.isBooleanValueType()); assertFalse(STRING_OBJECT_TYPE.isDateType()); assertFalse(STRING_OBJECT_TYPE.isEnumElementType()); assertFalse(STRING_OBJECT_TYPE.isNamedType()); assertFalse(STRING_OBJECT_TYPE.isNullType()); assertFalse(STRING_OBJECT_TYPE.isNumber()); assertFalse(STRING_OBJECT_TYPE.isNumberObjectType()); assertFalse(STRING_OBJECT_TYPE.isNumberValueType()); assertFalse(STRING_OBJECT_TYPE.isFunctionPrototypeType()); assertTrue( STRING_OBJECT_TYPE.getImplicitPrototype().isFunctionPrototypeType()); assertFalse(STRING_OBJECT_TYPE.isRegexpType()); assertTrue(STRING_OBJECT_TYPE.isString()); assertTrue(STRING_OBJECT_TYPE.isStringObjectType()); assertFalse(STRING_OBJECT_TYPE.isStringValueType()); assertFalse(STRING_OBJECT_TYPE.isEnumType()); assertFalse(STRING_OBJECT_TYPE.isUnionType()); assertFalse(STRING_OBJECT_TYPE.isStruct()); assertFalse(STRING_OBJECT_TYPE.isDict()); assertFalse(STRING_OBJECT_TYPE.isAllType()); assertFalse(STRING_OBJECT_TYPE.isVoidType()); assertFalse(STRING_OBJECT_TYPE.isConstructor()); assertTrue(STRING_OBJECT_TYPE.isInstanceType()); // autoboxesTo assertTypeEquals(STRING_OBJECT_TYPE, STRING_TYPE.autoboxesTo()); // unboxesTo assertTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.unboxesTo()); // isSubtype assertTrue(STRING_OBJECT_TYPE.isSubtype(ALL_TYPE)); assertTrue(STRING_OBJECT_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(STRING_OBJECT_TYPE.isSubtype(STRING_TYPE)); assertTrue(STRING_OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(STRING_OBJECT_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(STRING_OBJECT_TYPE.isSubtype(DATE_TYPE)); assertFalse(STRING_OBJECT_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(STRING_OBJECT_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(STRING_OBJECT_TYPE.isSubtype(STRING_TYPE)); // canBeCalled assertFalse(STRING_OBJECT_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(STRING_OBJECT_TYPE, ALL_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, STRING_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, functionType); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, BOOLEAN_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, BOOLEAN_OBJECT_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, DATE_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, ARRAY_TYPE); assertCanTestForEqualityWith(STRING_OBJECT_TYPE, UNKNOWN_TYPE); // canTestForShallowEqualityWith assertTrue(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertTrue(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(STRING_OBJECT_TYPE. canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(STRING_OBJECT_TYPE.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // properties (ECMA-262 page 98 - 106) assertEquals(23, STRING_OBJECT_TYPE.getImplicitPrototype(). getPropertiesCount()); assertEquals(24, STRING_OBJECT_TYPE.getPropertiesCount()); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("toString")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("valueOf")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("charAt")); assertReturnTypeEquals(NUMBER_TYPE, STRING_OBJECT_TYPE.getPropertyType("charCodeAt")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("concat")); assertReturnTypeEquals(NUMBER_TYPE, STRING_OBJECT_TYPE.getPropertyType("indexOf")); assertReturnTypeEquals(NUMBER_TYPE, STRING_OBJECT_TYPE.getPropertyType("lastIndexOf")); assertReturnTypeEquals(NUMBER_TYPE, STRING_OBJECT_TYPE.getPropertyType("localeCompare")); assertReturnTypeEquals(createNullableType(ARRAY_TYPE), STRING_OBJECT_TYPE.getPropertyType("match")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("replace")); assertReturnTypeEquals(NUMBER_TYPE, STRING_OBJECT_TYPE.getPropertyType("search")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("slice")); assertReturnTypeEquals(ARRAY_TYPE, STRING_OBJECT_TYPE.getPropertyType("split")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("substring")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("toLowerCase")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("toLocaleLowerCase")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("toUpperCase")); assertReturnTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.getPropertyType("toLocaleUpperCase")); assertTypeEquals(NUMBER_TYPE, STRING_OBJECT_TYPE.getPropertyType("length")); // matchesXxx assertTrue(STRING_OBJECT_TYPE.matchesInt32Context()); assertTrue(STRING_OBJECT_TYPE.matchesNumberContext()); assertTrue(STRING_OBJECT_TYPE.matchesObjectContext()); assertTrue(STRING_OBJECT_TYPE.matchesStringContext()); assertTrue(STRING_OBJECT_TYPE.matchesUint32Context()); // isNullable assertFalse(STRING_OBJECT_TYPE.isNullable()); assertTrue(createNullableType(STRING_OBJECT_TYPE).isNullable()); assertTrue(STRING_OBJECT_TYPE.isNativeObjectType()); Asserts.assertResolvesToSame(STRING_OBJECT_TYPE); assertTrue(STRING_OBJECT_TYPE.hasDisplayName()); assertEquals("String", STRING_OBJECT_TYPE.getDisplayName()); assertFalse(STRING_OBJECT_TYPE.isNominalConstructor()); assertTrue(STRING_OBJECT_TYPE.getConstructor().isNominalConstructor()); } /** * Tests the behavior of the string value type. */ public void testStringValueType() throws Exception { // isXxx assertFalse(STRING_TYPE.isArrayType()); assertFalse(STRING_TYPE.isBooleanObjectType()); assertFalse(STRING_TYPE.isBooleanValueType()); assertFalse(STRING_TYPE.isDateType()); assertFalse(STRING_TYPE.isEnumElementType()); assertFalse(STRING_TYPE.isNamedType()); assertFalse(STRING_TYPE.isNullType()); assertFalse(STRING_TYPE.isNumber()); assertFalse(STRING_TYPE.isNumberObjectType()); assertFalse(STRING_TYPE.isNumberValueType()); assertFalse(STRING_TYPE.isFunctionPrototypeType()); assertFalse(STRING_TYPE.isRegexpType()); assertTrue(STRING_TYPE.isString()); assertFalse(STRING_TYPE.isStringObjectType()); assertTrue(STRING_TYPE.isStringValueType()); assertFalse(STRING_TYPE.isEnumType()); assertFalse(STRING_TYPE.isUnionType()); assertFalse(STRING_TYPE.isStruct()); assertFalse(STRING_TYPE.isDict()); assertFalse(STRING_TYPE.isAllType()); assertFalse(STRING_TYPE.isVoidType()); assertFalse(STRING_TYPE.isConstructor()); assertFalse(STRING_TYPE.isInstanceType()); // autoboxesTo assertTypeEquals(STRING_OBJECT_TYPE, STRING_TYPE.autoboxesTo()); // unboxesTo assertTypeEquals(STRING_TYPE, STRING_OBJECT_TYPE.unboxesTo()); // isSubtype assertTrue(STRING_TYPE.isSubtype(ALL_TYPE)); assertFalse(STRING_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(STRING_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(STRING_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(STRING_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(STRING_TYPE.isSubtype(DATE_TYPE)); assertFalse(STRING_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(STRING_TYPE.isSubtype(ARRAY_TYPE)); assertTrue(STRING_TYPE.isSubtype(STRING_TYPE)); assertTrue(STRING_TYPE.isSubtype(UNKNOWN_TYPE)); // canBeCalled assertFalse(STRING_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(STRING_TYPE, ALL_TYPE); assertCanTestForEqualityWith(STRING_TYPE, STRING_OBJECT_TYPE); assertCannotTestForEqualityWith(STRING_TYPE, functionType); assertCanTestForEqualityWith(STRING_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(STRING_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(STRING_TYPE, BOOLEAN_TYPE); assertCanTestForEqualityWith(STRING_TYPE, BOOLEAN_OBJECT_TYPE); assertCanTestForEqualityWith(STRING_TYPE, DATE_TYPE); assertCanTestForEqualityWith(STRING_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(STRING_TYPE, ARRAY_TYPE); assertCanTestForEqualityWith(STRING_TYPE, UNKNOWN_TYPE); // canTestForShallowEqualityWith assertTrue(STRING_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(STRING_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertTrue(STRING_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(STRING_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(STRING_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(STRING_TYPE.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // matchesXxx assertTrue(STRING_TYPE.matchesInt32Context()); assertTrue(STRING_TYPE.matchesNumberContext()); assertTrue(STRING_TYPE.matchesObjectContext()); assertTrue(STRING_TYPE.matchesStringContext()); assertTrue(STRING_TYPE.matchesUint32Context()); // isNullable assertFalse(STRING_TYPE.isNullable()); assertTrue(createNullableType(STRING_TYPE).isNullable()); // toString assertEquals("string", STRING_TYPE.toString()); assertTrue(STRING_TYPE.hasDisplayName()); assertEquals("string", STRING_TYPE.getDisplayName()); // findPropertyType assertTypeEquals(NUMBER_TYPE, STRING_TYPE.findPropertyType("length")); assertEquals(null, STRING_TYPE.findPropertyType("unknownProperty")); Asserts.assertResolvesToSame(STRING_TYPE); assertFalse(STRING_TYPE.isNominalConstructor()); } private void assertPropertyTypeDeclared(ObjectType ownerType, String prop) { assertTrue(ownerType.isPropertyTypeDeclared(prop)); assertFalse(ownerType.isPropertyTypeInferred(prop)); } private void assertPropertyTypeInferred(ObjectType ownerType, String prop) { assertFalse(ownerType.isPropertyTypeDeclared(prop)); assertTrue(ownerType.isPropertyTypeInferred(prop)); } private void assertPropertyTypeUnknown(ObjectType ownerType, String prop) { assertFalse(ownerType.isPropertyTypeDeclared(prop)); assertFalse(ownerType.isPropertyTypeInferred(prop)); assertTrue(ownerType.getPropertyType(prop).isUnknownType()); } private void assertReturnTypeEquals(JSType expectedReturnType, JSType function) { assertTrue(function instanceof FunctionType); assertTypeEquals(expectedReturnType, ((FunctionType) function).getReturnType()); } /** * Tests the behavior of record types. */ public void testRecordType() throws Exception { // isXxx assertTrue(recordType.isObject()); assertFalse(recordType.isFunctionPrototypeType()); // isSubtype assertTrue(recordType.isSubtype(ALL_TYPE)); assertFalse(recordType.isSubtype(STRING_OBJECT_TYPE)); assertFalse(recordType.isSubtype(NUMBER_TYPE)); assertFalse(recordType.isSubtype(DATE_TYPE)); assertFalse(recordType.isSubtype(REGEXP_TYPE)); assertTrue(recordType.isSubtype(UNKNOWN_TYPE)); assertTrue(recordType.isSubtype(OBJECT_TYPE)); assertFalse(recordType.isSubtype(U2U_CONSTRUCTOR_TYPE)); // autoboxesTo assertNull(recordType.autoboxesTo()); // canBeCalled assertFalse(recordType.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(recordType, ALL_TYPE); assertCanTestForEqualityWith(recordType, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(recordType, recordType); assertCanTestForEqualityWith(recordType, functionType); assertCanTestForEqualityWith(recordType, OBJECT_TYPE); assertCanTestForEqualityWith(recordType, NUMBER_TYPE); assertCanTestForEqualityWith(recordType, DATE_TYPE); assertCanTestForEqualityWith(recordType, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(recordType.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(recordType.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(recordType. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(recordType.canTestForShallowEqualityWith(recordType)); assertFalse(recordType.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(recordType.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(recordType. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(recordType.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(recordType.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(recordType.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // matchesXxx assertFalse(recordType.matchesInt32Context()); assertFalse(recordType.matchesNumberContext()); assertTrue(recordType.matchesObjectContext()); assertFalse(recordType.matchesStringContext()); assertFalse(recordType.matchesUint32Context()); Asserts.assertResolvesToSame(recordType); } /** * Tests the behavior of the instance of Function. */ public void testFunctionInstanceType() throws Exception { FunctionType functionInst = FUNCTION_INSTANCE_TYPE; // isXxx assertTrue(functionInst.isObject()); assertFalse(functionInst.isFunctionPrototypeType()); assertTrue(functionInst.getImplicitPrototype() .isFunctionPrototypeType()); // isSubtype assertTrue(functionInst.isSubtype(ALL_TYPE)); assertFalse(functionInst.isSubtype(STRING_OBJECT_TYPE)); assertFalse(functionInst.isSubtype(NUMBER_TYPE)); assertFalse(functionInst.isSubtype(DATE_TYPE)); assertFalse(functionInst.isSubtype(REGEXP_TYPE)); assertTrue(functionInst.isSubtype(UNKNOWN_TYPE)); assertTrue(functionInst.isSubtype(U2U_CONSTRUCTOR_TYPE)); // autoboxesTo assertNull(functionInst.autoboxesTo()); // canBeCalled assertTrue(functionInst.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(functionInst, ALL_TYPE); assertCanTestForEqualityWith(functionInst, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(functionInst, functionInst); assertCanTestForEqualityWith(functionInst, OBJECT_TYPE); assertCannotTestForEqualityWith(functionInst, NUMBER_TYPE); assertCanTestForEqualityWith(functionInst, DATE_TYPE); assertCanTestForEqualityWith(functionInst, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(functionInst.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(functionInst.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(functionInst. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(functionInst.canTestForShallowEqualityWith(functionInst)); assertFalse(functionInst.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(functionInst.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(functionInst. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(functionInst.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(functionInst.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(functionInst.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // matchesXxx assertFalse(functionInst.matchesInt32Context()); assertFalse(functionInst.matchesNumberContext()); assertTrue(functionInst.matchesObjectContext()); assertFalse(functionInst.matchesStringContext()); assertFalse(functionInst.matchesUint32Context()); // hasProperty assertTrue(functionInst.hasProperty("prototype")); assertPropertyTypeInferred(functionInst, "prototype"); // misc assertTypeEquals(FUNCTION_FUNCTION_TYPE, functionInst.getConstructor()); assertTypeEquals(FUNCTION_PROTOTYPE, functionInst.getImplicitPrototype()); assertTypeEquals(functionInst, FUNCTION_FUNCTION_TYPE.getInstanceType()); Asserts.assertResolvesToSame(functionInst); } /** * Tests the behavior of functional types. */ public void testFunctionType() throws Exception { // isXxx assertTrue(functionType.isObject()); assertFalse(functionType.isFunctionPrototypeType()); assertTrue(functionType.getImplicitPrototype().getImplicitPrototype() .isFunctionPrototypeType()); // isSubtype assertTrue(functionType.isSubtype(ALL_TYPE)); assertFalse(functionType.isSubtype(STRING_OBJECT_TYPE)); assertFalse(functionType.isSubtype(NUMBER_TYPE)); assertFalse(functionType.isSubtype(DATE_TYPE)); assertFalse(functionType.isSubtype(REGEXP_TYPE)); assertTrue(functionType.isSubtype(UNKNOWN_TYPE)); assertTrue(functionType.isSubtype(U2U_CONSTRUCTOR_TYPE)); // autoboxesTo assertNull(functionType.autoboxesTo()); // canBeCalled assertTrue(functionType.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(functionType, ALL_TYPE); assertCanTestForEqualityWith(functionType, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(functionType, functionType); assertCanTestForEqualityWith(functionType, OBJECT_TYPE); assertCannotTestForEqualityWith(functionType, NUMBER_TYPE); assertCanTestForEqualityWith(functionType, DATE_TYPE); assertCanTestForEqualityWith(functionType, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(functionType.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(functionType.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(functionType. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertTrue(functionType.canTestForShallowEqualityWith(functionType)); assertFalse(functionType.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(functionType.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(functionType. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(functionType.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(functionType.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(functionType.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // matchesXxx assertFalse(functionType.matchesInt32Context()); assertFalse(functionType.matchesNumberContext()); assertTrue(functionType.matchesObjectContext()); assertFalse(functionType.matchesStringContext()); assertFalse(functionType.matchesUint32Context()); // hasProperty assertTrue(functionType.hasProperty("prototype")); assertPropertyTypeInferred(functionType, "prototype"); Asserts.assertResolvesToSame(functionType); assertEquals("aFunctionName", new FunctionBuilder(registry). withName("aFunctionName").build().getDisplayName()); } /** * Tests the subtyping relation of record types. */ public void testRecordTypeSubtyping() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); builder.addProperty("c", STRING_TYPE, null); JSType subRecordType = builder.build(); assertTrue(subRecordType.isSubtype(recordType)); assertFalse(recordType.isSubtype(subRecordType)); builder = new RecordTypeBuilder(registry); builder.addProperty("a", OBJECT_TYPE, null); builder.addProperty("b", STRING_TYPE, null); JSType differentRecordType = builder.build(); assertFalse(differentRecordType.isSubtype(recordType)); assertFalse(recordType.isSubtype(differentRecordType)); } /** * Tests the subtyping relation of record types when an object has * an inferred property.. */ public void testRecordTypeSubtypingWithInferredProperties() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", googSubBarInst, null); JSType record = builder.build(); ObjectType subtypeProp = registry.createAnonymousObjectType(null); subtypeProp.defineInferredProperty("a", googSubSubBarInst, null); assertTrue(subtypeProp.isSubtype(record)); assertFalse(record.isSubtype(subtypeProp)); ObjectType supertypeProp = registry.createAnonymousObjectType(null); supertypeProp.defineInferredProperty("a", googBarInst, null); assertFalse(supertypeProp.isSubtype(record)); assertFalse(record.isSubtype(supertypeProp)); ObjectType declaredSubtypeProp = registry.createAnonymousObjectType(null); declaredSubtypeProp.defineDeclaredProperty("a", googSubSubBarInst, null); assertFalse(declaredSubtypeProp.isSubtype(record)); assertFalse(record.isSubtype(declaredSubtypeProp)); } /** * Tests the getLeastSupertype method for record types. */ public void testRecordTypeLeastSuperType1() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); builder.addProperty("c", STRING_TYPE, null); JSType subRecordType = builder.build(); JSType leastSupertype = recordType.getLeastSupertype(subRecordType); assertTypeEquals(leastSupertype, recordType); } public void testRecordTypeLeastSuperType2() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("e", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); builder.addProperty("c", STRING_TYPE, null); JSType otherRecordType = builder.build(); assertTypeEquals( registry.createUnionType(recordType, otherRecordType), recordType.getLeastSupertype(otherRecordType)); } public void testRecordTypeLeastSuperType3() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("d", NUMBER_TYPE, null); builder.addProperty("e", STRING_TYPE, null); builder.addProperty("f", STRING_TYPE, null); JSType otherRecordType = builder.build(); assertTypeEquals( registry.createUnionType(recordType, otherRecordType), recordType.getLeastSupertype(otherRecordType)); } public void testRecordTypeLeastSuperType4() { JSType leastSupertype = recordType.getLeastSupertype(OBJECT_TYPE); assertTypeEquals(leastSupertype, OBJECT_TYPE); } /** * Tests the getGreatestSubtype method for record types. */ public void testRecordTypeGreatestSubType1() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("d", NUMBER_TYPE, null); builder.addProperty("e", STRING_TYPE, null); builder.addProperty("f", STRING_TYPE, null); JSType subRecordType = builder.build(); JSType subtype = recordType.getGreatestSubtype(subRecordType); builder = new RecordTypeBuilder(registry); builder.addProperty("d", NUMBER_TYPE, null); builder.addProperty("e", STRING_TYPE, null); builder.addProperty("f", STRING_TYPE, null); builder.addProperty("a", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); assertTypeEquals(subtype, builder.build()); } public void testRecordTypeGreatestSubType2() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); JSType subRecordType = builder.build(); JSType subtype = recordType.getGreatestSubtype(subRecordType); builder = new RecordTypeBuilder(registry); builder.addProperty("a", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); assertTypeEquals(subtype, builder.build()); } public void testRecordTypeGreatestSubType3() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); builder.addProperty("c", STRING_TYPE, null); JSType subRecordType = builder.build(); JSType subtype = recordType.getGreatestSubtype(subRecordType); builder = new RecordTypeBuilder(registry); builder.addProperty("a", NUMBER_TYPE, null); builder.addProperty("b", STRING_TYPE, null); builder.addProperty("c", STRING_TYPE, null); assertTypeEquals(subtype, builder.build()); } public void testRecordTypeGreatestSubType4() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", STRING_TYPE, null); builder.addProperty("b", STRING_TYPE, null); builder.addProperty("c", STRING_TYPE, null); JSType subRecordType = builder.build(); JSType subtype = recordType.getGreatestSubtype(subRecordType); assertTypeEquals(subtype, NO_TYPE); } public void testRecordTypeGreatestSubType5() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", STRING_TYPE, null); JSType recordType = builder.build(); assertTypeEquals(NO_OBJECT_TYPE, recordType.getGreatestSubtype(U2U_CONSTRUCTOR_TYPE)); // if Function is given a property "a" of type "string", then it's // a subtype of the record type {a: string}. U2U_CONSTRUCTOR_TYPE.defineDeclaredProperty("a", STRING_TYPE, null); assertTypeEquals(U2U_CONSTRUCTOR_TYPE, recordType.getGreatestSubtype(U2U_CONSTRUCTOR_TYPE)); assertTypeEquals(U2U_CONSTRUCTOR_TYPE, U2U_CONSTRUCTOR_TYPE.getGreatestSubtype(recordType)); } public void testRecordTypeGreatestSubType6() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("x", UNKNOWN_TYPE, null); JSType recordType = builder.build(); assertTypeEquals(NO_OBJECT_TYPE, recordType.getGreatestSubtype(U2U_CONSTRUCTOR_TYPE)); // if Function is given a property "x" of type "string", then it's // also a subtype of the record type {x: ?}. U2U_CONSTRUCTOR_TYPE.defineDeclaredProperty("x", STRING_TYPE, null); assertTypeEquals(U2U_CONSTRUCTOR_TYPE, recordType.getGreatestSubtype(U2U_CONSTRUCTOR_TYPE)); assertTypeEquals(U2U_CONSTRUCTOR_TYPE, U2U_CONSTRUCTOR_TYPE.getGreatestSubtype(recordType)); } public void testRecordTypeGreatestSubType7() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("x", NUMBER_TYPE, null); JSType recordType = builder.build(); // if Function is given a property "x" of type "string", then it's // not a subtype of the record type {x: number}. U2U_CONSTRUCTOR_TYPE.defineDeclaredProperty("x", STRING_TYPE, null); assertTypeEquals(NO_OBJECT_TYPE, recordType.getGreatestSubtype(U2U_CONSTRUCTOR_TYPE)); } public void testRecordTypeGreatestSubType8() { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("xyz", UNKNOWN_TYPE, null); JSType recordType = builder.build(); assertTypeEquals(NO_OBJECT_TYPE, recordType.getGreatestSubtype(U2U_CONSTRUCTOR_TYPE)); // if goog.Bar is given a property "xyz" of type "string", then it's // also a subtype of the record type {x: ?}. googBar.defineDeclaredProperty("xyz", STRING_TYPE, null); assertTypeEquals(googBar, recordType.getGreatestSubtype(U2U_CONSTRUCTOR_TYPE)); assertTypeEquals(googBar, U2U_CONSTRUCTOR_TYPE.getGreatestSubtype(recordType)); ObjectType googBarInst = googBar.getInstanceType(); assertTypeEquals(NO_OBJECT_TYPE, recordType.getGreatestSubtype(googBarInst)); assertTypeEquals(NO_OBJECT_TYPE, googBarInst.getGreatestSubtype(recordType)); } /** * Tests the "apply" method on the function type. */ public void testApplyOfDateMethod() { JSType applyType = dateMethod.getPropertyType("apply"); assertTrue("apply should be a function", applyType instanceof FunctionType); FunctionType applyFn = (FunctionType) applyType; assertTypeEquals("apply should have the same return type as its function", NUMBER_TYPE, applyFn.getReturnType()); Node params = applyFn.getParametersNode(); assertEquals("apply takes two args", 2, params.getChildCount()); assertTypeEquals("apply's first arg is the @this type", registry.createOptionalNullableType(DATE_TYPE), params.getFirstChild().getJSType()); assertTypeEquals("apply's second arg is an Array", registry.createOptionalNullableType(OBJECT_TYPE), params.getLastChild().getJSType()); assertTrue("apply's args must be optional", params.getFirstChild().isOptionalArg()); assertTrue("apply's args must be optional", params.getLastChild().isOptionalArg()); } /** * Tests the "call" method on the function type. */ public void testCallOfDateMethod() { JSType callType = dateMethod.getPropertyType("call"); assertTrue("call should be a function", callType instanceof FunctionType); FunctionType callFn = (FunctionType) callType; assertTypeEquals("call should have the same return type as its function", NUMBER_TYPE, callFn.getReturnType()); Node params = callFn.getParametersNode(); assertEquals("call takes one argument in this case", 1, params.getChildCount()); assertTypeEquals("call's first arg is the @this type", registry.createOptionalNullableType(DATE_TYPE), params.getFirstChild().getJSType()); assertTrue("call's args must be optional", params.getFirstChild().isOptionalArg()); } /** * Tests the representation of function types. */ public void testFunctionTypeRepresentation() { assertEquals("function (number, string): boolean", registry.createFunctionType(BOOLEAN_TYPE, false, NUMBER_TYPE, STRING_TYPE).toString()); assertEquals("function (new:Array, ...[*]): Array", ARRAY_FUNCTION_TYPE.toString()); assertEquals("function (new:Boolean, *=): boolean", BOOLEAN_OBJECT_FUNCTION_TYPE.toString()); assertEquals("function (new:Number, *=): number", NUMBER_OBJECT_FUNCTION_TYPE.toString()); assertEquals("function (new:String, *=): string", STRING_OBJECT_FUNCTION_TYPE.toString()); assertEquals("function (...[number]): boolean", registry.createFunctionType(BOOLEAN_TYPE, true, NUMBER_TYPE) .toString()); assertEquals("function (number, ...[string]): boolean", registry.createFunctionType(BOOLEAN_TYPE, true, NUMBER_TYPE, STRING_TYPE).toString()); assertEquals("function (this:Date, number): (boolean|number|string)", new FunctionBuilder(registry) .withParamsNode(registry.createParameters(NUMBER_TYPE)) .withReturnType(NUMBER_STRING_BOOLEAN) .withTypeOfThis(DATE_TYPE) .build().toString()); } /** * Tests relationships between structural function types. */ public void testFunctionTypeRelationships() { FunctionType dateMethodEmpty = new FunctionBuilder(registry) .withParamsNode(registry.createParameters()) .withTypeOfThis(DATE_TYPE).build(); FunctionType dateMethodWithParam = new FunctionBuilder(registry) .withParamsNode(registry.createOptionalParameters(NUMBER_TYPE)) .withTypeOfThis(DATE_TYPE).build(); FunctionType dateMethodWithReturn = new FunctionBuilder(registry) .withReturnType(NUMBER_TYPE) .withTypeOfThis(DATE_TYPE).build(); FunctionType stringMethodEmpty = new FunctionBuilder(registry) .withParamsNode(registry.createParameters()) .withTypeOfThis(STRING_OBJECT_TYPE).build(); FunctionType stringMethodWithParam = new FunctionBuilder(registry) .withParamsNode(registry.createOptionalParameters(NUMBER_TYPE)) .withTypeOfThis(STRING_OBJECT_TYPE).build(); FunctionType stringMethodWithReturn = new FunctionBuilder(registry) .withReturnType(NUMBER_TYPE) .withTypeOfThis(STRING_OBJECT_TYPE).build(); // One-off tests. assertFalse(stringMethodEmpty.isSubtype(dateMethodEmpty)); // Systemic tests. List<FunctionType> allFunctions = Lists.newArrayList( dateMethodEmpty, dateMethodWithParam, dateMethodWithReturn, stringMethodEmpty, stringMethodWithParam, stringMethodWithReturn); for (int i = 0; i < allFunctions.size(); i++) { for (int j = 0; j < allFunctions.size(); j++) { FunctionType typeA = allFunctions.get(i); FunctionType typeB = allFunctions.get(j); assertEquals(String.format("equals(%s, %s)", typeA, typeB), i == j, typeA.isEquivalentTo(typeB)); // For this particular set of functions, the functions are subtypes // of each other iff they have the same "this" type. assertEquals(String.format("isSubtype(%s, %s)", typeA, typeB), typeA.getTypeOfThis().isEquivalentTo(typeB.getTypeOfThis()), typeA.isSubtype(typeB)); if (i == j) { assertTypeEquals(typeA, typeA.getLeastSupertype(typeB)); assertTypeEquals(typeA, typeA.getGreatestSubtype(typeB)); } else { assertTypeEquals(String.format("sup(%s, %s)", typeA, typeB), U2U_CONSTRUCTOR_TYPE, typeA.getLeastSupertype(typeB)); assertTypeEquals(String.format("inf(%s, %s)", typeA, typeB), LEAST_FUNCTION_TYPE, typeA.getGreatestSubtype(typeB)); } } } } public void testProxiedFunctionTypeRelationships() { FunctionType dateMethodEmpty = new FunctionBuilder(registry) .withParamsNode(registry.createParameters()) .withTypeOfThis(DATE_TYPE).build().toMaybeFunctionType(); FunctionType dateMethodWithParam = new FunctionBuilder(registry) .withParamsNode(registry.createParameters(NUMBER_TYPE)) .withTypeOfThis(DATE_TYPE).build().toMaybeFunctionType(); ProxyObjectType proxyDateMethodEmpty = new ProxyObjectType(registry, dateMethodEmpty); ProxyObjectType proxyDateMethodWithParam = new ProxyObjectType(registry, dateMethodWithParam); assertTypeEquals(U2U_CONSTRUCTOR_TYPE, proxyDateMethodEmpty.getLeastSupertype(proxyDateMethodWithParam)); assertTypeEquals(LEAST_FUNCTION_TYPE, proxyDateMethodEmpty.getGreatestSubtype(proxyDateMethodWithParam)); } /** * Tests relationships between structural function types. */ public void testFunctionSubTypeRelationships() { FunctionType googBarMethod = new FunctionBuilder(registry) .withTypeOfThis(googBar).build(); FunctionType googBarParamFn = new FunctionBuilder(registry) .withParamsNode(registry.createParameters(googBar)).build(); FunctionType googBarReturnFn = new FunctionBuilder(registry) .withParamsNode(registry.createParameters()) .withReturnType(googBar).build(); FunctionType googSubBarMethod = new FunctionBuilder(registry) .withTypeOfThis(googSubBar).build(); FunctionType googSubBarParamFn = new FunctionBuilder(registry) .withParamsNode(registry.createParameters(googSubBar)).build(); FunctionType googSubBarReturnFn = new FunctionBuilder(registry) .withReturnType(googSubBar).build(); assertTrue(googBarMethod.isSubtype(googSubBarMethod)); assertTrue(googBarReturnFn.isSubtype(googSubBarReturnFn)); List<FunctionType> allFunctions = Lists.newArrayList( googBarMethod, googBarParamFn, googBarReturnFn, googSubBarMethod, googSubBarParamFn, googSubBarReturnFn); for (int i = 0; i < allFunctions.size(); i++) { for (int j = 0; j < allFunctions.size(); j++) { FunctionType typeA = allFunctions.get(i); FunctionType typeB = allFunctions.get(j); assertEquals(String.format("equals(%s, %s)", typeA, typeB), i == j, typeA.isEquivalentTo(typeB)); // TODO(nicksantos): This formulation of least subtype and greatest // supertype is a bit loose. We might want to tighten it up later. if (i == j) { assertTypeEquals(typeA, typeA.getLeastSupertype(typeB)); assertTypeEquals(typeA, typeA.getGreatestSubtype(typeB)); } else { assertTypeEquals(String.format("sup(%s, %s)", typeA, typeB), U2U_CONSTRUCTOR_TYPE, typeA.getLeastSupertype(typeB)); assertTypeEquals(String.format("inf(%s, %s)", typeA, typeB), LEAST_FUNCTION_TYPE, typeA.getGreatestSubtype(typeB)); } } } } /** * Tests that defining a property of a function's {@code prototype} adds the * property to it instance type. */ public void testFunctionPrototypeAndImplicitPrototype1() { FunctionType constructor = registry.createConstructorType("Foo", null, null, null, null); ObjectType instance = constructor.getInstanceType(); // adding one property on the prototype ObjectType prototype = (ObjectType) constructor.getPropertyType("prototype"); prototype.defineDeclaredProperty("foo", DATE_TYPE, null); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instance.getPropertiesCount()); } /** * Tests that replacing a function's {@code prototype} changes the visible * properties of its instance type. */ public void testFunctionPrototypeAndImplicitPrototype2() { FunctionType constructor = registry.createConstructorType(null, null, null, null); ObjectType instance = constructor.getInstanceType(); // replacing the prototype ObjectType prototype = registry.createAnonymousObjectType(null); prototype.defineDeclaredProperty("foo", DATE_TYPE, null); constructor.defineDeclaredProperty("prototype", prototype, null); assertEquals(NATIVE_PROPERTIES_COUNT + 1, instance.getPropertiesCount()); } /** Tests assigning JsDoc on a prototype property. */ public void testJSDocOnPrototypeProperty() throws Exception { subclassCtor.setPropertyJSDocInfo("prototype", new JSDocInfo()); assertNull(subclassCtor.getOwnPropertyJSDocInfo("prototype")); } /** * Tests the behavior of the void type. */ public void testVoidType() throws Exception { // isSubtype assertTrue(VOID_TYPE.isSubtype(ALL_TYPE)); assertFalse(VOID_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(VOID_TYPE.isSubtype(REGEXP_TYPE)); // autoboxesTo assertNull(VOID_TYPE.autoboxesTo()); // canTestForEqualityWith assertCanTestForEqualityWith(VOID_TYPE, ALL_TYPE); assertCannotTestForEqualityWith(VOID_TYPE, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(VOID_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(VOID_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(VOID_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertTrue(VOID_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(VOID_TYPE.canTestForShallowEqualityWith( createUnionType(NUMBER_TYPE, VOID_TYPE))); // matchesXxx assertFalse(VOID_TYPE.matchesInt32Context()); assertFalse(VOID_TYPE.matchesNumberContext()); assertFalse(VOID_TYPE.matchesObjectContext()); assertTrue(VOID_TYPE.matchesStringContext()); assertFalse(VOID_TYPE.matchesUint32Context()); Asserts.assertResolvesToSame(VOID_TYPE); } /** * Tests the behavior of the boolean type. */ public void testBooleanValueType() throws Exception { // isXxx assertFalse(BOOLEAN_TYPE.isArrayType()); assertFalse(BOOLEAN_TYPE.isBooleanObjectType()); assertTrue(BOOLEAN_TYPE.isBooleanValueType()); assertFalse(BOOLEAN_TYPE.isDateType()); assertFalse(BOOLEAN_TYPE.isEnumElementType()); assertFalse(BOOLEAN_TYPE.isNamedType()); assertFalse(BOOLEAN_TYPE.isNullType()); assertFalse(BOOLEAN_TYPE.isNumberObjectType()); assertFalse(BOOLEAN_TYPE.isNumberValueType()); assertFalse(BOOLEAN_TYPE.isFunctionPrototypeType()); assertFalse(BOOLEAN_TYPE.isRegexpType()); assertFalse(BOOLEAN_TYPE.isStringObjectType()); assertFalse(BOOLEAN_TYPE.isStringValueType()); assertFalse(BOOLEAN_TYPE.isEnumType()); assertFalse(BOOLEAN_TYPE.isUnionType()); assertFalse(BOOLEAN_TYPE.isStruct()); assertFalse(BOOLEAN_TYPE.isDict()); assertFalse(BOOLEAN_TYPE.isAllType()); assertFalse(BOOLEAN_TYPE.isVoidType()); assertFalse(BOOLEAN_TYPE.isConstructor()); assertFalse(BOOLEAN_TYPE.isInstanceType()); // autoboxesTo assertTypeEquals(BOOLEAN_OBJECT_TYPE, BOOLEAN_TYPE.autoboxesTo()); // unboxesTo assertTypeEquals(BOOLEAN_TYPE, BOOLEAN_OBJECT_TYPE.unboxesTo()); // isSubtype assertTrue(BOOLEAN_TYPE.isSubtype(ALL_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(functionType)); assertFalse(BOOLEAN_TYPE.isSubtype(NULL_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(DATE_TYPE)); assertTrue(BOOLEAN_TYPE.isSubtype(unresolvedNamedType)); assertFalse(BOOLEAN_TYPE.isSubtype(namedGoogBar)); assertFalse(BOOLEAN_TYPE.isSubtype(REGEXP_TYPE)); // canBeCalled assertFalse(BOOLEAN_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(BOOLEAN_TYPE, ALL_TYPE); assertCanTestForEqualityWith(BOOLEAN_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(BOOLEAN_TYPE, NUMBER_TYPE); assertCannotTestForEqualityWith(BOOLEAN_TYPE, functionType); assertCannotTestForEqualityWith(BOOLEAN_TYPE, VOID_TYPE); assertCanTestForEqualityWith(BOOLEAN_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(BOOLEAN_TYPE, DATE_TYPE); assertCanTestForEqualityWith(BOOLEAN_TYPE, REGEXP_TYPE); assertCanTestForEqualityWith(BOOLEAN_TYPE, UNKNOWN_TYPE); // canTestForShallowEqualityWith assertTrue(BOOLEAN_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertTrue(BOOLEAN_TYPE.canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertFalse(BOOLEAN_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(functionType)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(BOOLEAN_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(BOOLEAN_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); assertTrue(BOOLEAN_TYPE.canTestForShallowEqualityWith(UNKNOWN_TYPE)); // isNullable assertFalse(BOOLEAN_TYPE.isNullable()); // matchesXxx assertTrue(BOOLEAN_TYPE.matchesInt32Context()); assertTrue(BOOLEAN_TYPE.matchesNumberContext()); assertTrue(BOOLEAN_TYPE.matchesObjectContext()); assertTrue(BOOLEAN_TYPE.matchesStringContext()); assertTrue(BOOLEAN_TYPE.matchesUint32Context()); // toString assertEquals("boolean", BOOLEAN_TYPE.toString()); assertTrue(BOOLEAN_TYPE.hasDisplayName()); assertEquals("boolean", BOOLEAN_TYPE.getDisplayName()); Asserts.assertResolvesToSame(BOOLEAN_TYPE); } /** * Tests the behavior of the Boolean type. */ public void testBooleanObjectType() throws Exception { // isXxx assertFalse(BOOLEAN_OBJECT_TYPE.isArrayType()); assertTrue(BOOLEAN_OBJECT_TYPE.isBooleanObjectType()); assertFalse(BOOLEAN_OBJECT_TYPE.isBooleanValueType()); assertFalse(BOOLEAN_OBJECT_TYPE.isDateType()); assertFalse(BOOLEAN_OBJECT_TYPE.isEnumElementType()); assertFalse(BOOLEAN_OBJECT_TYPE.isNamedType()); assertFalse(BOOLEAN_OBJECT_TYPE.isNullType()); assertFalse(BOOLEAN_OBJECT_TYPE.isNumberObjectType()); assertFalse(BOOLEAN_OBJECT_TYPE.isNumberValueType()); assertFalse(BOOLEAN_OBJECT_TYPE.isFunctionPrototypeType()); assertTrue( BOOLEAN_OBJECT_TYPE.getImplicitPrototype().isFunctionPrototypeType()); assertFalse(BOOLEAN_OBJECT_TYPE.isRegexpType()); assertFalse(BOOLEAN_OBJECT_TYPE.isStringObjectType()); assertFalse(BOOLEAN_OBJECT_TYPE.isStringValueType()); assertFalse(BOOLEAN_OBJECT_TYPE.isEnumType()); assertFalse(BOOLEAN_OBJECT_TYPE.isUnionType()); assertFalse(BOOLEAN_OBJECT_TYPE.isStruct()); assertFalse(BOOLEAN_OBJECT_TYPE.isDict()); assertFalse(BOOLEAN_OBJECT_TYPE.isAllType()); assertFalse(BOOLEAN_OBJECT_TYPE.isVoidType()); assertFalse(BOOLEAN_OBJECT_TYPE.isConstructor()); assertTrue(BOOLEAN_OBJECT_TYPE.isInstanceType()); // isSubtype assertTrue(BOOLEAN_OBJECT_TYPE.isSubtype(ALL_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(functionType)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(NULL_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(DATE_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE.isSubtype(unresolvedNamedType)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(namedGoogBar)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(REGEXP_TYPE)); // canBeCalled assertFalse(BOOLEAN_OBJECT_TYPE.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(BOOLEAN_OBJECT_TYPE, ALL_TYPE); assertCanTestForEqualityWith(BOOLEAN_OBJECT_TYPE, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(BOOLEAN_OBJECT_TYPE, NUMBER_TYPE); assertCanTestForEqualityWith(BOOLEAN_OBJECT_TYPE, functionType); assertCannotTestForEqualityWith(BOOLEAN_OBJECT_TYPE, VOID_TYPE); assertCanTestForEqualityWith(BOOLEAN_OBJECT_TYPE, OBJECT_TYPE); assertCanTestForEqualityWith(BOOLEAN_OBJECT_TYPE, DATE_TYPE); assertCanTestForEqualityWith(BOOLEAN_OBJECT_TYPE, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(BOOLEAN_OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(functionType)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE. canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(BOOLEAN_OBJECT_TYPE.isNullable()); // matchesXxx assertTrue(BOOLEAN_OBJECT_TYPE.matchesInt32Context()); assertTrue(BOOLEAN_OBJECT_TYPE.matchesNumberContext()); assertTrue(BOOLEAN_OBJECT_TYPE.matchesObjectContext()); assertTrue(BOOLEAN_OBJECT_TYPE.matchesStringContext()); assertTrue(BOOLEAN_OBJECT_TYPE.matchesUint32Context()); // toString assertEquals("Boolean", BOOLEAN_OBJECT_TYPE.toString()); assertTrue(BOOLEAN_OBJECT_TYPE.hasDisplayName()); assertEquals("Boolean", BOOLEAN_OBJECT_TYPE.getDisplayName()); assertTrue(BOOLEAN_OBJECT_TYPE.isNativeObjectType()); Asserts.assertResolvesToSame(BOOLEAN_OBJECT_TYPE); } /** * Tests the behavior of the enum type. */ public void testEnumType() throws Exception { EnumType enumType = new EnumType(registry, "Enum", null, NUMBER_TYPE); // isXxx assertFalse(enumType.isArrayType()); assertFalse(enumType.isBooleanObjectType()); assertFalse(enumType.isBooleanValueType()); assertFalse(enumType.isDateType()); assertFalse(enumType.isEnumElementType()); assertFalse(enumType.isNamedType()); assertFalse(enumType.isNullType()); assertFalse(enumType.isNumberObjectType()); assertFalse(enumType.isNumberValueType()); assertFalse(enumType.isFunctionPrototypeType()); assertFalse(enumType.isRegexpType()); assertFalse(enumType.isStringObjectType()); assertFalse(enumType.isStringValueType()); assertTrue(enumType.isEnumType()); assertFalse(enumType.isUnionType()); assertFalse(enumType.isStruct()); assertFalse(enumType.isDict()); assertFalse(enumType.isAllType()); assertFalse(enumType.isVoidType()); assertFalse(enumType.isConstructor()); assertFalse(enumType.isInstanceType()); // isSubtype assertTrue(enumType.isSubtype(ALL_TYPE)); assertFalse(enumType.isSubtype(STRING_OBJECT_TYPE)); assertFalse(enumType.isSubtype(NUMBER_TYPE)); assertFalse(enumType.isSubtype(functionType)); assertFalse(enumType.isSubtype(NULL_TYPE)); assertTrue(enumType.isSubtype(OBJECT_TYPE)); assertFalse(enumType.isSubtype(DATE_TYPE)); assertTrue(enumType.isSubtype(unresolvedNamedType)); assertFalse(enumType.isSubtype(namedGoogBar)); assertFalse(enumType.isSubtype(REGEXP_TYPE)); // canBeCalled assertFalse(enumType.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(enumType, ALL_TYPE); assertCanTestForEqualityWith(enumType, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(enumType, NUMBER_TYPE); assertCanTestForEqualityWith(enumType, functionType); assertCannotTestForEqualityWith(enumType, VOID_TYPE); assertCanTestForEqualityWith(enumType, OBJECT_TYPE); assertCanTestForEqualityWith(enumType, DATE_TYPE); assertCanTestForEqualityWith(enumType, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(enumType.canTestForShallowEqualityWith(NO_TYPE)); assertTrue(enumType. canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(enumType.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue(enumType. canTestForShallowEqualityWith(enumType)); assertFalse(enumType.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(enumType.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(functionType)); assertFalse(enumType.canTestForShallowEqualityWith(NULL_TYPE)); assertFalse(enumType.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertTrue(enumType.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(enumType.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(enumType.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(enumType. canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(enumType.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(enumType.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(enumType.isNullable()); // matchesXxx assertFalse(enumType.matchesInt32Context()); assertFalse(enumType.matchesNumberContext()); assertTrue(enumType.matchesObjectContext()); assertTrue(enumType.matchesStringContext()); assertFalse(enumType.matchesUint32Context()); // toString assertEquals("enum{Enum}", enumType.toString()); assertTrue(enumType.hasDisplayName()); assertEquals("Enum", enumType.getDisplayName()); assertEquals("AnotherEnum", new EnumType(registry, "AnotherEnum", null, NUMBER_TYPE).getDisplayName()); assertFalse( new EnumType(registry, null, null, NUMBER_TYPE).hasDisplayName()); Asserts.assertResolvesToSame(enumType); } /** * Tests the behavior of the enum element type. */ public void testEnumElementType() throws Exception { // isXxx assertFalse(elementsType.isArrayType()); assertFalse(elementsType.isBooleanObjectType()); assertFalse(elementsType.isBooleanValueType()); assertFalse(elementsType.isDateType()); assertTrue(elementsType.isEnumElementType()); assertFalse(elementsType.isNamedType()); assertFalse(elementsType.isNullType()); assertFalse(elementsType.isNumberObjectType()); assertFalse(elementsType.isNumberValueType()); assertFalse(elementsType.isFunctionPrototypeType()); assertFalse(elementsType.isRegexpType()); assertFalse(elementsType.isStringObjectType()); assertFalse(elementsType.isStringValueType()); assertFalse(elementsType.isEnumType()); assertFalse(elementsType.isUnionType()); assertFalse(elementsType.isStruct()); assertFalse(elementsType.isDict()); assertFalse(elementsType.isAllType()); assertFalse(elementsType.isVoidType()); assertFalse(elementsType.isConstructor()); assertFalse(elementsType.isInstanceType()); // isSubtype assertTrue(elementsType.isSubtype(ALL_TYPE)); assertFalse(elementsType.isSubtype(STRING_OBJECT_TYPE)); assertTrue(elementsType.isSubtype(NUMBER_TYPE)); assertFalse(elementsType.isSubtype(functionType)); assertFalse(elementsType.isSubtype(NULL_TYPE)); assertFalse(elementsType.isSubtype(OBJECT_TYPE)); // no more autoboxing assertFalse(elementsType.isSubtype(DATE_TYPE)); assertTrue(elementsType.isSubtype(unresolvedNamedType)); assertFalse(elementsType.isSubtype(namedGoogBar)); assertFalse(elementsType.isSubtype(REGEXP_TYPE)); // canBeCalled assertFalse(elementsType.canBeCalled()); // canTestForEqualityWith assertCanTestForEqualityWith(elementsType, ALL_TYPE); assertCanTestForEqualityWith(elementsType, STRING_OBJECT_TYPE); assertCanTestForEqualityWith(elementsType, NUMBER_TYPE); assertCanTestForEqualityWith(elementsType, NUMBER_OBJECT_TYPE); assertCanTestForEqualityWith(elementsType, elementsType); assertCannotTestForEqualityWith(elementsType, functionType); assertCannotTestForEqualityWith(elementsType, VOID_TYPE); assertCanTestForEqualityWith(elementsType, OBJECT_TYPE); assertCanTestForEqualityWith(elementsType, DATE_TYPE); assertCanTestForEqualityWith(elementsType, REGEXP_TYPE); // canTestForShallowEqualityWith assertTrue(elementsType.canTestForShallowEqualityWith(NO_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(NO_OBJECT_TYPE)); assertFalse(elementsType.canTestForShallowEqualityWith(ARRAY_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(BOOLEAN_TYPE)); assertTrue(elementsType. canTestForShallowEqualityWith(elementsType)); assertFalse(elementsType.canTestForShallowEqualityWith(DATE_TYPE)); assertFalse(elementsType.canTestForShallowEqualityWith(ERROR_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(EVAL_ERROR_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(functionType)); assertFalse(elementsType.canTestForShallowEqualityWith(NULL_TYPE)); assertTrue(elementsType.canTestForShallowEqualityWith(NUMBER_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(NUMBER_OBJECT_TYPE)); assertFalse(elementsType.canTestForShallowEqualityWith(OBJECT_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(URI_ERROR_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(RANGE_ERROR_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(REFERENCE_ERROR_TYPE)); assertFalse(elementsType.canTestForShallowEqualityWith(REGEXP_TYPE)); assertFalse(elementsType.canTestForShallowEqualityWith(STRING_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(STRING_OBJECT_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(SYNTAX_ERROR_TYPE)); assertFalse(elementsType. canTestForShallowEqualityWith(TYPE_ERROR_TYPE)); assertTrue(elementsType.canTestForShallowEqualityWith(ALL_TYPE)); assertFalse(elementsType.canTestForShallowEqualityWith(VOID_TYPE)); // isNullable assertFalse(elementsType.isNullable()); // matchesXxx assertTrue(elementsType.matchesInt32Context()); assertTrue(elementsType.matchesNumberContext()); assertTrue(elementsType.matchesObjectContext()); assertTrue(elementsType.matchesStringContext()); assertTrue(elementsType.matchesUint32Context()); // toString assertEquals("Enum.<number>", elementsType.toString()); assertTrue(elementsType.hasDisplayName()); assertEquals("Enum", elementsType.getDisplayName()); Asserts.assertResolvesToSame(elementsType); } public void testStringEnumType() throws Exception { EnumElementType stringEnum = new EnumType(registry, "Enum", null, STRING_TYPE).getElementsType(); assertTypeEquals(UNKNOWN_TYPE, stringEnum.getPropertyType("length")); assertTypeEquals(NUMBER_TYPE, stringEnum.findPropertyType("length")); assertEquals(false, stringEnum.hasProperty("length")); assertTypeEquals(STRING_OBJECT_TYPE, stringEnum.autoboxesTo()); assertNull(stringEnum.getConstructor()); Asserts.assertResolvesToSame(stringEnum); } public void testStringObjectEnumType() throws Exception { EnumElementType stringEnum = new EnumType(registry, "Enum", null, STRING_OBJECT_TYPE) .getElementsType(); assertTypeEquals(NUMBER_TYPE, stringEnum.getPropertyType("length")); assertTypeEquals(NUMBER_TYPE, stringEnum.findPropertyType("length")); assertEquals(true, stringEnum.hasProperty("length")); assertTypeEquals(STRING_OBJECT_FUNCTION_TYPE, stringEnum.getConstructor()); } /** * Tests object types. */ public void testObjectType() throws Exception { PrototypeObjectType objectType = new PrototypeObjectType(registry, null, null); // isXxx assertFalse(objectType.isAllType()); assertFalse(objectType.isArrayType()); assertFalse(objectType.isDateType()); assertFalse(objectType.isFunctionPrototypeType()); assertTrue(objectType.getImplicitPrototype() == OBJECT_TYPE); // isSubtype assertTrue(objectType.isSubtype(ALL_TYPE)); assertFalse(objectType.isSubtype(STRING_OBJECT_TYPE)); assertFalse(objectType.isSubtype(NUMBER_TYPE)); assertFalse(objectType.isSubtype(functionType)); assertFalse(objectType.isSubtype(NULL_TYPE)); assertFalse(objectType.isSubtype(DATE_TYPE)); assertTrue(objectType.isSubtype(OBJECT_TYPE)); assertTrue(objectType.isSubtype(unresolvedNamedType)); assertFalse(objectType.isSubtype(namedGoogBar)); assertFalse(objectType.isSubtype(REGEXP_TYPE)); // autoboxesTo assertNull(objectType.autoboxesTo()); // canTestForEqualityWith assertCanTestForEqualityWith(objectType, NUMBER_TYPE); // matchesXxxContext assertFalse(objectType.matchesInt32Context()); assertFalse(objectType.matchesNumberContext()); assertTrue(objectType.matchesObjectContext()); assertFalse(objectType.matchesStringContext()); assertFalse(objectType.matchesUint32Context()); // isNullable assertFalse(objectType.isNullable()); assertTrue(createNullableType(objectType).isNullable()); // toString assertEquals("{...}", objectType.toString()); assertEquals(null, objectType.getDisplayName()); assertFalse(objectType.hasReferenceName()); assertEquals("anObject", new PrototypeObjectType(registry, "anObject", null).getDisplayName()); Asserts.assertResolvesToSame(objectType); } /** * Tests the goog.Bar type. */ public void testGoogBar() throws Exception { assertTrue(namedGoogBar.isInstanceType()); assertFalse(googBar.isInstanceType()); assertFalse(namedGoogBar.isConstructor()); assertTrue(googBar.isConstructor()); assertTrue(googBar.getInstanceType().isInstanceType()); assertTrue(namedGoogBar.getConstructor().isConstructor()); assertTrue(namedGoogBar.getImplicitPrototype().isFunctionPrototypeType()); // isSubtype assertTypeCanAssignToItself(googBar); assertTypeCanAssignToItself(namedGoogBar); googBar.isSubtype(namedGoogBar); namedGoogBar.isSubtype(googBar); assertTypeEquals(googBar, googBar); assertTypeNotEquals(googBar, googSubBar); Asserts.assertResolvesToSame(googBar); Asserts.assertResolvesToSame(googSubBar); } /** * Tests how properties are counted for object types. */ public void testObjectTypePropertiesCount() throws Exception { ObjectType sup = registry.createAnonymousObjectType(null); int nativeProperties = sup.getPropertiesCount(); sup.defineDeclaredProperty("a", DATE_TYPE, null); assertEquals(nativeProperties + 1, sup.getPropertiesCount()); sup.defineDeclaredProperty("b", DATE_TYPE, null); assertEquals(nativeProperties + 2, sup.getPropertiesCount()); ObjectType sub = registry.createObjectType(sup); assertEquals(nativeProperties + 2, sub.getPropertiesCount()); } /** * Tests how properties are defined. */ public void testDefineProperties() { ObjectType prototype = googBar.getPrototype(); ObjectType instance = googBar.getInstanceType(); assertTypeEquals(instance.getImplicitPrototype(), prototype); // Test declarations. assertTrue( prototype.defineDeclaredProperty("declared", NUMBER_TYPE, null)); assertFalse( prototype.defineDeclaredProperty("declared", NUMBER_TYPE, null)); assertFalse( instance.defineDeclaredProperty("declared", NUMBER_TYPE, null)); assertTypeEquals(NUMBER_TYPE, instance.getPropertyType("declared")); // Test inferring different types. assertTrue(prototype.defineInferredProperty("inferred1", STRING_TYPE, null)); assertTrue(prototype.defineInferredProperty("inferred1", NUMBER_TYPE, null)); assertTypeEquals( createUnionType(NUMBER_TYPE, STRING_TYPE), instance.getPropertyType("inferred1")); // Test inferring different types on different objects. assertTrue(prototype.defineInferredProperty("inferred2", STRING_TYPE, null)); assertTrue(instance.defineInferredProperty("inferred2", NUMBER_TYPE, null)); assertTypeEquals( createUnionType(NUMBER_TYPE, STRING_TYPE), instance.getPropertyType("inferred2")); // Test inferring on the supertype and declaring on the subtype. assertTrue( prototype.defineInferredProperty("prop", STRING_TYPE, null)); assertTrue( instance.defineDeclaredProperty("prop", NUMBER_TYPE, null)); assertTypeEquals(NUMBER_TYPE, instance.getPropertyType("prop")); assertTypeEquals(STRING_TYPE, prototype.getPropertyType("prop")); } /** * Tests that properties are correctly counted even when shadowing occurs. */ public void testObjectTypePropertiesCountWithShadowing() { ObjectType sup = registry.createAnonymousObjectType(null); int nativeProperties = sup.getPropertiesCount(); sup.defineDeclaredProperty("a", OBJECT_TYPE, null); assertEquals(nativeProperties + 1, sup.getPropertiesCount()); ObjectType sub = registry.createObjectType(sup); sub.defineDeclaredProperty("a", OBJECT_TYPE, null); assertEquals(nativeProperties + 1, sub.getPropertiesCount()); } /** * Tests the named type goog.Bar. */ public void testNamedGoogBar() throws Exception { // isXxx assertFalse(namedGoogBar.isFunctionPrototypeType()); assertTrue(namedGoogBar.getImplicitPrototype().isFunctionPrototypeType()); // isSubtype assertTrue(namedGoogBar.isSubtype(ALL_TYPE)); assertFalse(namedGoogBar.isSubtype(STRING_OBJECT_TYPE)); assertFalse(namedGoogBar.isSubtype(NUMBER_TYPE)); assertFalse(namedGoogBar.isSubtype(functionType)); assertFalse(namedGoogBar.isSubtype(NULL_TYPE)); assertTrue(namedGoogBar.isSubtype(OBJECT_TYPE)); assertFalse(namedGoogBar.isSubtype(DATE_TYPE)); assertTrue(namedGoogBar.isSubtype(namedGoogBar)); assertTrue(namedGoogBar.isSubtype(unresolvedNamedType)); assertFalse(namedGoogBar.isSubtype(REGEXP_TYPE)); assertFalse(namedGoogBar.isSubtype(ARRAY_TYPE)); // autoboxesTo assertNull(namedGoogBar.autoboxesTo()); // properties assertTypeEquals(DATE_TYPE, namedGoogBar.getPropertyType("date")); assertFalse(namedGoogBar.isNativeObjectType()); assertFalse(namedGoogBar.getImplicitPrototype().isNativeObjectType()); JSType resolvedNamedGoogBar = Asserts.assertValidResolve(namedGoogBar); assertNotSame(resolvedNamedGoogBar, namedGoogBar); assertSame(resolvedNamedGoogBar, googBar.getInstanceType()); } /** * Tests the prototype chaining of native objects. */ public void testPrototypeChaining() throws Exception { // equals assertTypeEquals( ARRAY_TYPE.getImplicitPrototype().getImplicitPrototype(), OBJECT_TYPE); assertTypeEquals( BOOLEAN_OBJECT_TYPE.getImplicitPrototype(). getImplicitPrototype(), OBJECT_TYPE); assertTypeEquals( DATE_TYPE.getImplicitPrototype().getImplicitPrototype(), OBJECT_TYPE); assertTypeEquals( ERROR_TYPE.getImplicitPrototype().getImplicitPrototype(), OBJECT_TYPE); assertTypeEquals( EVAL_ERROR_TYPE.getImplicitPrototype().getImplicitPrototype(), ERROR_TYPE); assertTypeEquals( NUMBER_OBJECT_TYPE.getImplicitPrototype(). getImplicitPrototype(), OBJECT_TYPE); assertTypeEquals( URI_ERROR_TYPE.getImplicitPrototype().getImplicitPrototype(), ERROR_TYPE); assertTypeEquals( RANGE_ERROR_TYPE.getImplicitPrototype().getImplicitPrototype(), ERROR_TYPE); assertTypeEquals( REFERENCE_ERROR_TYPE.getImplicitPrototype(). getImplicitPrototype(), ERROR_TYPE); assertTypeEquals( STRING_OBJECT_TYPE.getImplicitPrototype(). getImplicitPrototype(), OBJECT_TYPE); assertTypeEquals( REGEXP_TYPE.getImplicitPrototype().getImplicitPrototype(), OBJECT_TYPE); assertTypeEquals( SYNTAX_ERROR_TYPE.getImplicitPrototype(). getImplicitPrototype(), ERROR_TYPE); assertTypeEquals( TYPE_ERROR_TYPE.getImplicitPrototype(). getImplicitPrototype(), ERROR_TYPE); // not same assertNotSame(EVAL_ERROR_TYPE.getImplicitPrototype(), URI_ERROR_TYPE.getImplicitPrototype()); assertNotSame(EVAL_ERROR_TYPE.getImplicitPrototype(), RANGE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(EVAL_ERROR_TYPE.getImplicitPrototype(), REFERENCE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(EVAL_ERROR_TYPE.getImplicitPrototype(), SYNTAX_ERROR_TYPE.getImplicitPrototype()); assertNotSame(EVAL_ERROR_TYPE.getImplicitPrototype(), TYPE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(URI_ERROR_TYPE.getImplicitPrototype(), RANGE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(URI_ERROR_TYPE.getImplicitPrototype(), REFERENCE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(URI_ERROR_TYPE.getImplicitPrototype(), SYNTAX_ERROR_TYPE.getImplicitPrototype()); assertNotSame(URI_ERROR_TYPE.getImplicitPrototype(), TYPE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(RANGE_ERROR_TYPE.getImplicitPrototype(), REFERENCE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(RANGE_ERROR_TYPE.getImplicitPrototype(), SYNTAX_ERROR_TYPE.getImplicitPrototype()); assertNotSame(RANGE_ERROR_TYPE.getImplicitPrototype(), TYPE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(REFERENCE_ERROR_TYPE.getImplicitPrototype(), SYNTAX_ERROR_TYPE.getImplicitPrototype()); assertNotSame(REFERENCE_ERROR_TYPE.getImplicitPrototype(), TYPE_ERROR_TYPE.getImplicitPrototype()); assertNotSame(SYNTAX_ERROR_TYPE.getImplicitPrototype(), TYPE_ERROR_TYPE.getImplicitPrototype()); } /** * Tests that function instances have their constructor pointer back at the * function that created them. */ public void testInstanceFunctionChaining() throws Exception { // Array assertTypeEquals( ARRAY_FUNCTION_TYPE, ARRAY_TYPE.getConstructor()); // Boolean assertTypeEquals( BOOLEAN_OBJECT_FUNCTION_TYPE, BOOLEAN_OBJECT_TYPE.getConstructor()); // Date assertTypeEquals( DATE_FUNCTION_TYPE, DATE_TYPE.getConstructor()); // Error assertTypeEquals( ERROR_FUNCTION_TYPE, ERROR_TYPE.getConstructor()); // EvalError assertTypeEquals( EVAL_ERROR_FUNCTION_TYPE, EVAL_ERROR_TYPE.getConstructor()); // Number assertTypeEquals( NUMBER_OBJECT_FUNCTION_TYPE, NUMBER_OBJECT_TYPE.getConstructor()); // Object assertTypeEquals( OBJECT_FUNCTION_TYPE, OBJECT_TYPE.getConstructor()); // RangeError assertTypeEquals( RANGE_ERROR_FUNCTION_TYPE, RANGE_ERROR_TYPE.getConstructor()); // ReferenceError assertTypeEquals( REFERENCE_ERROR_FUNCTION_TYPE, REFERENCE_ERROR_TYPE.getConstructor()); // RegExp assertTypeEquals(REGEXP_FUNCTION_TYPE, REGEXP_TYPE.getConstructor()); // String assertTypeEquals( STRING_OBJECT_FUNCTION_TYPE, STRING_OBJECT_TYPE.getConstructor()); // SyntaxError assertTypeEquals( SYNTAX_ERROR_FUNCTION_TYPE, SYNTAX_ERROR_TYPE.getConstructor()); // TypeError assertTypeEquals( TYPE_ERROR_FUNCTION_TYPE, TYPE_ERROR_TYPE.getConstructor()); // URIError assertTypeEquals( URI_ERROR_FUNCTION_TYPE, URI_ERROR_TYPE.getConstructor()); } /** * Tests that the method {@link JSType#canTestForEqualityWith(JSType)} handles * special corner cases. */ @SuppressWarnings("checked") public void testCanTestForEqualityWithCornerCases() { // null == undefined is always true assertCannotTestForEqualityWith(NULL_TYPE, VOID_TYPE); // (Object,null) == undefined could be true or false UnionType nullableObject = (UnionType) createUnionType(OBJECT_TYPE, NULL_TYPE); assertCanTestForEqualityWith(nullableObject, VOID_TYPE); assertCanTestForEqualityWith(VOID_TYPE, nullableObject); } /** * Tests the {@link JSType#testForEquality(JSType)} method. */ public void testTestForEquality() { compare(TRUE, NO_OBJECT_TYPE, NO_OBJECT_TYPE); compare(UNKNOWN, ALL_TYPE, ALL_TYPE); compare(TRUE, NO_TYPE, NO_TYPE); compare(UNKNOWN, NO_RESOLVED_TYPE, NO_RESOLVED_TYPE); compare(UNKNOWN, NO_OBJECT_TYPE, NUMBER_TYPE); compare(UNKNOWN, ALL_TYPE, NUMBER_TYPE); compare(UNKNOWN, NO_TYPE, NUMBER_TYPE); compare(FALSE, NULL_TYPE, BOOLEAN_TYPE); compare(TRUE, NULL_TYPE, NULL_TYPE); compare(FALSE, NULL_TYPE, NUMBER_TYPE); compare(FALSE, NULL_TYPE, OBJECT_TYPE); compare(FALSE, NULL_TYPE, STRING_TYPE); compare(TRUE, NULL_TYPE, VOID_TYPE); compare(UNKNOWN, NULL_TYPE, createUnionType(UNKNOWN_TYPE, VOID_TYPE)); compare(UNKNOWN, NULL_TYPE, createUnionType(OBJECT_TYPE, VOID_TYPE)); compare(UNKNOWN, NULL_TYPE, unresolvedNamedType); compare(UNKNOWN, NULL_TYPE, createUnionType(unresolvedNamedType, DATE_TYPE)); compare(FALSE, VOID_TYPE, REGEXP_TYPE); compare(TRUE, VOID_TYPE, VOID_TYPE); compare(UNKNOWN, VOID_TYPE, createUnionType(REGEXP_TYPE, VOID_TYPE)); compare(UNKNOWN, NUMBER_TYPE, BOOLEAN_TYPE); compare(UNKNOWN, NUMBER_TYPE, NUMBER_TYPE); compare(UNKNOWN, NUMBER_TYPE, OBJECT_TYPE); compare(UNKNOWN, ARRAY_TYPE, BOOLEAN_TYPE); compare(UNKNOWN, OBJECT_TYPE, BOOLEAN_TYPE); compare(UNKNOWN, OBJECT_TYPE, STRING_TYPE); compare(UNKNOWN, STRING_TYPE, STRING_TYPE); compare(UNKNOWN, STRING_TYPE, BOOLEAN_TYPE); compare(UNKNOWN, STRING_TYPE, NUMBER_TYPE); compare(FALSE, STRING_TYPE, VOID_TYPE); compare(FALSE, STRING_TYPE, NULL_TYPE); compare(FALSE, STRING_TYPE, createUnionType(NULL_TYPE, VOID_TYPE)); compare(UNKNOWN, UNKNOWN_TYPE, BOOLEAN_TYPE); compare(UNKNOWN, UNKNOWN_TYPE, NULL_TYPE); compare(UNKNOWN, UNKNOWN_TYPE, VOID_TYPE); compare(FALSE, U2U_CONSTRUCTOR_TYPE, BOOLEAN_TYPE); compare(FALSE, U2U_CONSTRUCTOR_TYPE, NUMBER_TYPE); compare(FALSE, U2U_CONSTRUCTOR_TYPE, STRING_TYPE); compare(FALSE, U2U_CONSTRUCTOR_TYPE, VOID_TYPE); compare(FALSE, U2U_CONSTRUCTOR_TYPE, NULL_TYPE); compare(UNKNOWN, U2U_CONSTRUCTOR_TYPE, OBJECT_TYPE); compare(UNKNOWN, U2U_CONSTRUCTOR_TYPE, ALL_TYPE); compare(UNKNOWN, NULL_TYPE, subclassOfUnresolvedNamedType); JSType functionAndNull = createUnionType(NULL_TYPE, dateMethod); compare(UNKNOWN, functionAndNull, dateMethod); compare(UNKNOWN, NULL_TYPE, NO_TYPE); compare(UNKNOWN, VOID_TYPE, NO_TYPE); compare(UNKNOWN, NULL_TYPE, unresolvedNamedType); compare(UNKNOWN, VOID_TYPE, unresolvedNamedType); compare(TRUE, NO_TYPE, NO_TYPE); } private void compare(TernaryValue r, JSType t1, JSType t2) { assertEquals(r, t1.testForEquality(t2)); assertEquals(r, t2.testForEquality(t1)); } private void assertCanTestForEqualityWith(JSType t1, JSType t2) { assertTrue(t1.canTestForEqualityWith(t2)); assertTrue(t2.canTestForEqualityWith(t1)); } private void assertCannotTestForEqualityWith(JSType t1, JSType t2) { assertFalse(t1.canTestForEqualityWith(t2)); assertFalse(t2.canTestForEqualityWith(t1)); } /** * Tests the subtyping relationships among simple types. */ public void testSubtypingSimpleTypes() throws Exception { // Any assertTrue(NO_TYPE.isSubtype(NO_TYPE)); assertTrue(NO_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(ARRAY_TYPE)); assertTrue(NO_TYPE.isSubtype(BOOLEAN_TYPE)); assertTrue(NO_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(DATE_TYPE)); assertTrue(NO_TYPE.isSubtype(ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(functionType)); assertTrue(NO_TYPE.isSubtype(NULL_TYPE)); assertTrue(NO_TYPE.isSubtype(NUMBER_TYPE)); assertTrue(NO_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(URI_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(REGEXP_TYPE)); assertTrue(NO_TYPE.isSubtype(STRING_TYPE)); assertTrue(NO_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertTrue(NO_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(NO_TYPE.isSubtype(ALL_TYPE)); assertTrue(NO_TYPE.isSubtype(VOID_TYPE)); // AnyObject assertFalse(NO_OBJECT_TYPE.isSubtype(NO_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(BOOLEAN_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(DATE_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(functionType)); assertFalse(NO_OBJECT_TYPE.isSubtype(NULL_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(NUMBER_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(URI_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(STRING_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(NO_OBJECT_TYPE.isSubtype(ALL_TYPE)); assertFalse(NO_OBJECT_TYPE.isSubtype(VOID_TYPE)); // Array assertFalse(ARRAY_TYPE.isSubtype(NO_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(NO_OBJECT_TYPE)); assertTrue(ARRAY_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(DATE_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(ERROR_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(functionType)); assertFalse(ARRAY_TYPE.isSubtype(NULL_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(ARRAY_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(STRING_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(ARRAY_TYPE.isSubtype(ALL_TYPE)); assertFalse(ARRAY_TYPE.isSubtype(VOID_TYPE)); // boolean assertFalse(BOOLEAN_TYPE.isSubtype(NO_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(ARRAY_TYPE)); assertTrue(BOOLEAN_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(DATE_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(functionType)); assertFalse(BOOLEAN_TYPE.isSubtype(NULL_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(STRING_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(BOOLEAN_TYPE.isSubtype(ALL_TYPE)); assertFalse(BOOLEAN_TYPE.isSubtype(VOID_TYPE)); // Boolean assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(NO_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(BOOLEAN_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(DATE_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(functionType)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(NULL_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(STRING_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(BOOLEAN_OBJECT_TYPE.isSubtype(ALL_TYPE)); assertFalse(BOOLEAN_OBJECT_TYPE.isSubtype(VOID_TYPE)); // Date assertFalse(DATE_TYPE.isSubtype(NO_TYPE)); assertFalse(DATE_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(DATE_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(DATE_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(DATE_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertTrue(DATE_TYPE.isSubtype(DATE_TYPE)); assertFalse(DATE_TYPE.isSubtype(ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(functionType)); assertFalse(DATE_TYPE.isSubtype(NULL_TYPE)); assertFalse(DATE_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(DATE_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(DATE_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(DATE_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(DATE_TYPE.isSubtype(STRING_TYPE)); assertFalse(DATE_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(DATE_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(DATE_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(DATE_TYPE.isSubtype(ALL_TYPE)); assertFalse(DATE_TYPE.isSubtype(VOID_TYPE)); // Error assertFalse(ERROR_TYPE.isSubtype(NO_TYPE)); assertFalse(ERROR_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(ERROR_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(ERROR_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(ERROR_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(ERROR_TYPE.isSubtype(DATE_TYPE)); assertTrue(ERROR_TYPE.isSubtype(ERROR_TYPE)); assertFalse(ERROR_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(ERROR_TYPE.isSubtype(functionType)); assertFalse(ERROR_TYPE.isSubtype(NULL_TYPE)); assertFalse(ERROR_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(ERROR_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(ERROR_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(ERROR_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(ERROR_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(ERROR_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(ERROR_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(ERROR_TYPE.isSubtype(STRING_TYPE)); assertFalse(ERROR_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(ERROR_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(ERROR_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(ERROR_TYPE.isSubtype(ALL_TYPE)); assertFalse(ERROR_TYPE.isSubtype(VOID_TYPE)); // EvalError assertFalse(EVAL_ERROR_TYPE.isSubtype(NO_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(ERROR_TYPE.isSubtype(DATE_TYPE)); assertTrue(EVAL_ERROR_TYPE.isSubtype(ERROR_TYPE)); assertTrue(EVAL_ERROR_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(functionType)); assertFalse(EVAL_ERROR_TYPE.isSubtype(NULL_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertTrue(EVAL_ERROR_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(STRING_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(EVAL_ERROR_TYPE.isSubtype(ALL_TYPE)); assertFalse(EVAL_ERROR_TYPE.isSubtype(VOID_TYPE)); // RangeError assertTrue(RANGE_ERROR_TYPE.isSubtype(ERROR_TYPE)); // ReferenceError assertTrue(REFERENCE_ERROR_TYPE.isSubtype(ERROR_TYPE)); // TypeError assertTrue(TYPE_ERROR_TYPE.isSubtype(ERROR_TYPE)); // UriError assertTrue(URI_ERROR_TYPE.isSubtype(ERROR_TYPE)); // Unknown assertFalse(ALL_TYPE.isSubtype(NO_TYPE)); assertFalse(ALL_TYPE.isSubtype(NO_OBJECT_TYPE)); assertFalse(ALL_TYPE.isSubtype(ARRAY_TYPE)); assertFalse(ALL_TYPE.isSubtype(BOOLEAN_TYPE)); assertFalse(ALL_TYPE.isSubtype(BOOLEAN_OBJECT_TYPE)); assertFalse(ERROR_TYPE.isSubtype(DATE_TYPE)); assertFalse(ALL_TYPE.isSubtype(ERROR_TYPE)); assertFalse(ALL_TYPE.isSubtype(EVAL_ERROR_TYPE)); assertFalse(ALL_TYPE.isSubtype(functionType)); assertFalse(ALL_TYPE.isSubtype(NULL_TYPE)); assertFalse(ALL_TYPE.isSubtype(NUMBER_TYPE)); assertFalse(ALL_TYPE.isSubtype(NUMBER_OBJECT_TYPE)); assertFalse(ALL_TYPE.isSubtype(OBJECT_TYPE)); assertFalse(ALL_TYPE.isSubtype(URI_ERROR_TYPE)); assertFalse(ALL_TYPE.isSubtype(RANGE_ERROR_TYPE)); assertFalse(ALL_TYPE.isSubtype(REFERENCE_ERROR_TYPE)); assertFalse(ALL_TYPE.isSubtype(REGEXP_TYPE)); assertFalse(ALL_TYPE.isSubtype(STRING_TYPE)); assertFalse(ALL_TYPE.isSubtype(STRING_OBJECT_TYPE)); assertFalse(ALL_TYPE.isSubtype(SYNTAX_ERROR_TYPE)); assertFalse(ALL_TYPE.isSubtype(TYPE_ERROR_TYPE)); assertTrue(ALL_TYPE.isSubtype(ALL_TYPE)); assertFalse(ALL_TYPE.isSubtype(VOID_TYPE)); } /** * Tests that the Object type is the greatest element (top) of the object * hierarchy. */ public void testSubtypingObjectTopOfObjects() throws Exception { assertTrue(OBJECT_TYPE.isSubtype(OBJECT_TYPE)); assertTrue(createUnionType(DATE_TYPE, REGEXP_TYPE).isSubtype(OBJECT_TYPE)); assertTrue(createUnionType(OBJECT_TYPE, NO_OBJECT_TYPE). isSubtype(OBJECT_TYPE)); assertTrue(functionType.isSubtype(OBJECT_TYPE)); } public void testSubtypingFunctionPrototypeType() throws Exception { FunctionType sub1 = registry.createConstructorType(null, null, null, null); sub1.setPrototypeBasedOn(googBar); FunctionType sub2 = registry.createConstructorType(null, null, null, null); sub2.setPrototypeBasedOn(googBar); ObjectType o1 = sub1.getInstanceType(); ObjectType o2 = sub2.getInstanceType(); assertFalse(o1.isSubtype(o2)); assertFalse(o1.getImplicitPrototype().isSubtype(o2.getImplicitPrototype())); assertTrue(o1.getImplicitPrototype().isSubtype(googBar)); assertTrue(o2.getImplicitPrototype().isSubtype(googBar)); } public void testSubtypingFunctionFixedArgs() throws Exception { FunctionType f1 = registry.createFunctionType(OBJECT_TYPE, false, BOOLEAN_TYPE); FunctionType f2 = registry.createFunctionType(STRING_OBJECT_TYPE, false, BOOLEAN_TYPE); assertTrue(f1.isSubtype(f1)); assertFalse(f1.isSubtype(f2)); assertTrue(f2.isSubtype(f1)); assertTrue(f2.isSubtype(f2)); assertTrue(f1.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(f2.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f1)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f2)); } public void testSubtypingFunctionMultipleFixedArgs() throws Exception { FunctionType f1 = registry.createFunctionType(OBJECT_TYPE, false, EVAL_ERROR_TYPE, STRING_TYPE); FunctionType f2 = registry.createFunctionType(STRING_OBJECT_TYPE, false, ERROR_TYPE, ALL_TYPE); assertTrue(f1.isSubtype(f1)); assertFalse(f1.isSubtype(f2)); assertTrue(f2.isSubtype(f1)); assertTrue(f2.isSubtype(f2)); assertTrue(f1.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(f2.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f1)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f2)); } public void testSubtypingFunctionFixedArgsNotMatching() throws Exception { FunctionType f1 = registry.createFunctionType(OBJECT_TYPE, false, EVAL_ERROR_TYPE, UNKNOWN_TYPE); FunctionType f2 = registry.createFunctionType(STRING_OBJECT_TYPE, false, ERROR_TYPE, ALL_TYPE); assertTrue(f1.isSubtype(f1)); assertFalse(f1.isSubtype(f2)); assertTrue(f2.isSubtype(f1)); assertTrue(f2.isSubtype(f2)); assertTrue(f1.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(f2.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f1)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f2)); } public void testSubtypingFunctionVariableArgsOneOnly() throws Exception { // f1 = (EvalError...) -> Object FunctionType f1 = registry.createFunctionType(OBJECT_TYPE, true, EVAL_ERROR_TYPE); // f2 = (Error, Object) -> String FunctionType f2 = registry.createFunctionType(STRING_OBJECT_TYPE, false, ERROR_TYPE, OBJECT_TYPE); assertTrue(f1.isSubtype(f1)); assertFalse(f1.isSubtype(f2)); assertFalse(f2.isSubtype(f1)); assertTrue(f2.isSubtype(f2)); assertTrue(f1.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(f2.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f1)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f2)); } public void testSubtypingFunctionVariableArgsBoth() throws Exception { // f1 = (UriError, EvalError, EvalError...) -> Object FunctionType f1 = registry.createFunctionType(OBJECT_TYPE, true, URI_ERROR_TYPE, EVAL_ERROR_TYPE, EVAL_ERROR_TYPE); // f2 = (Error, Object, EvalError...) -> String FunctionType f2 = registry.createFunctionType(STRING_OBJECT_TYPE, true, ERROR_TYPE, OBJECT_TYPE, EVAL_ERROR_TYPE); assertTrue(f1.isSubtype(f1)); assertFalse(f1.isSubtype(f2)); assertTrue(f2.isSubtype(f1)); assertTrue(f2.isSubtype(f2)); assertTrue(f1.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(f2.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f1)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(f2)); } public void testSubtypingMostGeneralFunction() throws Exception { // (EvalError, String) -> Object FunctionType f1 = registry.createFunctionType(OBJECT_TYPE, false, EVAL_ERROR_TYPE, STRING_TYPE); // (string, void) -> number FunctionType f2 = registry.createFunctionType(NUMBER_TYPE, false, STRING_TYPE, VOID_TYPE); // (Date, string, number) -> AnyObject FunctionType f3 = registry.createFunctionType(NO_OBJECT_TYPE, false, DATE_TYPE, STRING_TYPE, NUMBER_TYPE); // (Number) -> Any FunctionType f4 = registry.createFunctionType(NO_TYPE, false, NUMBER_OBJECT_TYPE); // f1 = (EvalError...) -> Object FunctionType f5 = registry.createFunctionType(OBJECT_TYPE, true, EVAL_ERROR_TYPE); // f2 = (Error, Object) -> String FunctionType f6 = registry.createFunctionType(STRING_OBJECT_TYPE, false, ERROR_TYPE, OBJECT_TYPE); // f1 = (UriError, EvalError...) -> Object FunctionType f7 = registry.createFunctionType(OBJECT_TYPE, true, URI_ERROR_TYPE, EVAL_ERROR_TYPE); // f2 = (Error, Object, EvalError...) -> String FunctionType f8 = registry.createFunctionType(STRING_OBJECT_TYPE, true, ERROR_TYPE, OBJECT_TYPE, EVAL_ERROR_TYPE); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(LEAST_FUNCTION_TYPE)); assertTrue(GREATEST_FUNCTION_TYPE.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f1.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f2.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f3.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f4.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f5.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f6.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f7.isSubtype(GREATEST_FUNCTION_TYPE)); assertTrue(f8.isSubtype(GREATEST_FUNCTION_TYPE)); assertFalse(f1.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(f2.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(f3.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(f4.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(f5.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(f6.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(f7.isSubtype(LEAST_FUNCTION_TYPE)); assertFalse(f8.isSubtype(LEAST_FUNCTION_TYPE)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f1)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f2)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f3)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f4)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f5)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f6)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f7)); assertTrue(LEAST_FUNCTION_TYPE.isSubtype(f8)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f1)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f2)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f3)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f4)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f5)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f6)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f7)); assertFalse(GREATEST_FUNCTION_TYPE.isSubtype(f8)); } /** * Types to test for symmetrical relationships. */ private List<JSType> getTypesToTestForSymmetry() { return Lists.newArrayList( UNKNOWN_TYPE, NULL_TYPE, VOID_TYPE, NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE, OBJECT_TYPE, U2U_CONSTRUCTOR_TYPE, LEAST_FUNCTION_TYPE, GREATEST_FUNCTION_TYPE, ALL_TYPE, NO_TYPE, NO_OBJECT_TYPE, NO_RESOLVED_TYPE, createUnionType(BOOLEAN_TYPE, STRING_TYPE), createUnionType(NUMBER_TYPE, STRING_TYPE), createUnionType(NULL_TYPE, dateMethod), createUnionType(UNKNOWN_TYPE, dateMethod), createUnionType(namedGoogBar, dateMethod), createUnionType(NULL_TYPE, unresolvedNamedType), enumType, elementsType, dateMethod, functionType, unresolvedNamedType, googBar, namedGoogBar, googBar.getInstanceType(), namedGoogBar, subclassOfUnresolvedNamedType, subclassCtor, recordType, forwardDeclaredNamedType, createUnionType(forwardDeclaredNamedType, NULL_TYPE), createTemplatizedType(OBJECT_TYPE, STRING_TYPE), createTemplatizedType(OBJECT_TYPE, NUMBER_TYPE), createTemplatizedType(ARRAY_TYPE, STRING_TYPE), createTemplatizedType(ARRAY_TYPE, NUMBER_TYPE), createUnionType( createTemplatizedType(ARRAY_TYPE, BOOLEAN_TYPE), NULL_TYPE), createUnionType( createTemplatizedType(OBJECT_TYPE, BOOLEAN_TYPE), NULL_TYPE) ); } public void testSymmetryOfTestForEquality() { List<JSType> listA = getTypesToTestForSymmetry(); List<JSType> listB = getTypesToTestForSymmetry(); for (JSType typeA : listA) { for (JSType typeB : listB) { TernaryValue aOnB = typeA.testForEquality(typeB); TernaryValue bOnA = typeB.testForEquality(typeA); assertTrue( String.format("testForEquality not symmetrical:\n" + "typeA: %s\ntypeB: %s\n" + "a.testForEquality(b): %s\n" + "b.testForEquality(a): %s\n", typeA, typeB, aOnB, bOnA), aOnB == bOnA); } } } /** * Tests that getLeastSupertype is a symmetric relation. */ public void testSymmetryOfLeastSupertype() { List<JSType> listA = getTypesToTestForSymmetry(); List<JSType> listB = getTypesToTestForSymmetry(); for (JSType typeA : listA) { for (JSType typeB : listB) { JSType aOnB = typeA.getLeastSupertype(typeB); JSType bOnA = typeB.getLeastSupertype(typeA); // Use a custom assert message instead of the normal assertTypeEquals, // to make it more helpful. assertTrue( String.format("getLeastSupertype not symmetrical:\n" + "typeA: %s\ntypeB: %s\n" + "a.getLeastSupertype(b): %s\n" + "b.getLeastSupertype(a): %s\n", typeA, typeB, aOnB, bOnA), aOnB.isEquivalentTo(bOnA)); } } } public void testWeirdBug() { assertTypeNotEquals(googBar, googBar.getInstanceType()); assertFalse(googBar.isSubtype(googBar.getInstanceType())); assertFalse(googBar.getInstanceType().isSubtype(googBar)); } /** * Tests that getGreatestSubtype is a symmetric relation. */ public void testSymmetryOfGreatestSubtype() { List<JSType> listA = getTypesToTestForSymmetry(); List<JSType> listB = getTypesToTestForSymmetry(); for (JSType typeA : listA) { for (JSType typeB : listB) { JSType aOnB = typeA.getGreatestSubtype(typeB); JSType bOnA = typeB.getGreatestSubtype(typeA); // Use a custom assert message instead of the normal assertTypeEquals, // to make it more helpful. assertTrue( String.format("getGreatestSubtype not symmetrical:\n" + "typeA: %s\ntypeB: %s\n" + "a.getGreatestSubtype(b): %s\n" + "b.getGreatestSubtype(a): %s\n", typeA, typeB, aOnB, bOnA), aOnB.isEquivalentTo(bOnA)); } } } /** * Tests that getLeastSupertype is a reflexive relation. */ public void testReflexivityOfLeastSupertype() { List<JSType> list = getTypesToTestForSymmetry(); for (JSType type : list) { assertTypeEquals("getLeastSupertype not reflexive", type, type.getLeastSupertype(type)); } } /** * Tests that getGreatestSubtype is a reflexive relation. */ public void testReflexivityOfGreatestSubtype() { List<JSType> list = getTypesToTestForSymmetry(); for (JSType type : list) { assertTypeEquals("getGreatestSubtype not reflexive", type, type.getGreatestSubtype(type)); } } /** * Tests {@link JSType#getLeastSupertype(JSType)} for unresolved named types. */ public void testLeastSupertypeUnresolvedNamedType() { // (undefined,function(?):?) and ? unresolved named type JSType expected = registry.createUnionType( unresolvedNamedType, U2U_FUNCTION_TYPE); assertTypeEquals(expected, unresolvedNamedType.getLeastSupertype(U2U_FUNCTION_TYPE)); assertTypeEquals(expected, U2U_FUNCTION_TYPE.getLeastSupertype(unresolvedNamedType)); assertEquals("(function (...[?]): ?|not.resolved.named.type)", expected.toString()); } public void testLeastSupertypeUnresolvedNamedType2() { JSType expected = registry.createUnionType( unresolvedNamedType, UNKNOWN_TYPE); assertTypeEquals(expected, unresolvedNamedType.getLeastSupertype(UNKNOWN_TYPE)); assertTypeEquals(expected, UNKNOWN_TYPE.getLeastSupertype(unresolvedNamedType)); assertTypeEquals(UNKNOWN_TYPE, expected); } public void testLeastSupertypeUnresolvedNamedType3() { JSType expected = registry.createUnionType( unresolvedNamedType, CHECKED_UNKNOWN_TYPE); assertTypeEquals(expected, unresolvedNamedType.getLeastSupertype(CHECKED_UNKNOWN_TYPE)); assertTypeEquals(expected, CHECKED_UNKNOWN_TYPE.getLeastSupertype(unresolvedNamedType)); assertTypeEquals(CHECKED_UNKNOWN_TYPE, expected); } /** Tests the subclass of an unresolved named type */ public void testSubclassOfUnresolvedNamedType() { assertTrue(subclassOfUnresolvedNamedType.isUnknownType()); } /** * Tests that Proxied FunctionTypes behave the same over getLeastSupertype and * getGreatestSubtype as non proxied FunctionTypes */ public void testSupertypeOfProxiedFunctionTypes() { ObjectType fn1 = new FunctionBuilder(registry) .withParamsNode(new Node(Token.PARAM_LIST)) .withReturnType(NUMBER_TYPE) .build(); ObjectType fn2 = new FunctionBuilder(registry) .withParamsNode(new Node(Token.PARAM_LIST)) .withReturnType(STRING_TYPE) .build(); ObjectType p1 = new ProxyObjectType(registry, fn1); ObjectType p2 = new ProxyObjectType(registry, fn2); ObjectType supremum = new FunctionBuilder(registry) .withParamsNode(new Node(Token.PARAM_LIST)) .withReturnType(registry.createUnionType(STRING_TYPE, NUMBER_TYPE)) .build(); assertTypeEquals(fn1.getLeastSupertype(fn2), p1.getLeastSupertype(p2)); assertTypeEquals(supremum, fn1.getLeastSupertype(fn2)); assertTypeEquals(supremum, fn1.getLeastSupertype(p2)); assertTypeEquals(supremum, p1.getLeastSupertype(fn2)); assertTypeEquals(supremum, p1.getLeastSupertype(p2)); } public void testTypeOfThisIsProxied() { ObjectType fnType = new FunctionBuilder(registry) .withReturnType(NUMBER_TYPE).withTypeOfThis(OBJECT_TYPE).build(); ObjectType proxyType = new ProxyObjectType(registry, fnType); assertTypeEquals(fnType.getTypeOfThis(), proxyType.getTypeOfThis()); } /** * Tests the {@link NamedType#equals} function, which had a bug in it. */ public void testNamedTypeEquals() { JSTypeRegistry jst = new JSTypeRegistry(null); // test == if references are equal NamedType a = new NamedType(jst, "type1", "source", 1, 0); NamedType b = new NamedType(jst, "type1", "source", 1, 0); assertTrue(a.isEquivalentTo(b)); // test == instance of referenced type assertTrue(namedGoogBar.isEquivalentTo(googBar.getInstanceType())); assertTrue(googBar.getInstanceType().isEquivalentTo(namedGoogBar)); } /** * Tests the {@link NamedType#equals} function against other types. */ public void testNamedTypeEquals2() { // test == if references are equal NamedType a = new NamedType(registry, "typeA", "source", 1, 0); NamedType b = new NamedType(registry, "typeB", "source", 1, 0); ObjectType realA = registry.createConstructorType( "typeA", null, null, null, null).getInstanceType(); ObjectType realB = registry.createEnumType( "typeB", null, NUMBER_TYPE).getElementsType(); registry.declareType("typeA", realA); registry.declareType("typeB", realB); assertTypeEquals(a, realA); assertTypeEquals(b, realB); a.resolve(null, null); b.resolve(null, null); assertTrue(a.isResolved()); assertTrue(b.isResolved()); assertTypeEquals(a, realA); assertTypeEquals(b, realB); JSType resolvedA = Asserts.assertValidResolve(a); assertNotSame(resolvedA, a); assertSame(resolvedA, realA); JSType resolvedB = Asserts.assertValidResolve(b); assertNotSame(resolvedB, b); assertSame(resolvedB, realB); } /** * Tests the {@link NamedType#equals} function against other types * when it's forward-declared. */ public void testForwardDeclaredNamedTypeEquals() { // test == if references are equal NamedType a = new NamedType(registry, "typeA", "source", 1, 0); NamedType b = new NamedType(registry, "typeA", "source", 1, 0); registry.forwardDeclareType("typeA"); assertTypeEquals(a, b); a.resolve(null, EMPTY_SCOPE); assertTrue(a.isResolved()); assertFalse(b.isResolved()); assertTypeEquals(a, b); assertFalse(a.isEquivalentTo(UNKNOWN_TYPE)); assertFalse(b.isEquivalentTo(UNKNOWN_TYPE)); assertTrue(a.isEmptyType()); assertFalse(a.isNoType()); assertTrue(a.isNoResolvedType()); } public void testForwardDeclaredNamedType() { NamedType a = new NamedType(registry, "typeA", "source", 1, 0); registry.forwardDeclareType("typeA"); assertTypeEquals(UNKNOWN_TYPE, a.getLeastSupertype(UNKNOWN_TYPE)); assertTypeEquals(CHECKED_UNKNOWN_TYPE, a.getLeastSupertype(CHECKED_UNKNOWN_TYPE)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getLeastSupertype(a)); assertTypeEquals(CHECKED_UNKNOWN_TYPE, CHECKED_UNKNOWN_TYPE.getLeastSupertype(a)); } /** * Tests {@link JSType#getGreatestSubtype(JSType)} on simple types. */ public void testGreatestSubtypeSimpleTypes() { assertTypeEquals(ARRAY_TYPE, ARRAY_TYPE.getGreatestSubtype(ALL_TYPE)); assertTypeEquals(ARRAY_TYPE, ALL_TYPE.getGreatestSubtype(ARRAY_TYPE)); assertTypeEquals(NO_OBJECT_TYPE, REGEXP_TYPE.getGreatestSubtype(NO_OBJECT_TYPE)); assertTypeEquals(NO_OBJECT_TYPE, NO_OBJECT_TYPE.getGreatestSubtype(REGEXP_TYPE)); assertTypeEquals(NO_OBJECT_TYPE, ARRAY_TYPE.getGreatestSubtype(STRING_OBJECT_TYPE)); assertTypeEquals(NO_TYPE, ARRAY_TYPE.getGreatestSubtype(NUMBER_TYPE)); assertTypeEquals(NO_OBJECT_TYPE, ARRAY_TYPE.getGreatestSubtype(functionType)); assertTypeEquals(STRING_OBJECT_TYPE, STRING_OBJECT_TYPE.getGreatestSubtype(OBJECT_TYPE)); assertTypeEquals(STRING_OBJECT_TYPE, OBJECT_TYPE.getGreatestSubtype(STRING_OBJECT_TYPE)); assertTypeEquals(NO_OBJECT_TYPE, ARRAY_TYPE.getGreatestSubtype(DATE_TYPE)); assertTypeEquals(NO_OBJECT_TYPE, ARRAY_TYPE.getGreatestSubtype(REGEXP_TYPE)); assertTypeEquals(EVAL_ERROR_TYPE, ERROR_TYPE.getGreatestSubtype(EVAL_ERROR_TYPE)); assertTypeEquals(EVAL_ERROR_TYPE, EVAL_ERROR_TYPE.getGreatestSubtype(ERROR_TYPE)); assertTypeEquals(NO_TYPE, NULL_TYPE.getGreatestSubtype(ERROR_TYPE)); assertTypeEquals(UNKNOWN_TYPE, NUMBER_TYPE.getGreatestSubtype(UNKNOWN_TYPE)); assertTypeEquals(NO_RESOLVED_TYPE, NO_OBJECT_TYPE.getGreatestSubtype(forwardDeclaredNamedType)); assertTypeEquals(NO_RESOLVED_TYPE, forwardDeclaredNamedType.getGreatestSubtype(NO_OBJECT_TYPE)); } /** * Tests that a derived class extending a type via a named type is a subtype * of it. */ public void testSubtypingDerivedExtendsNamedBaseType() throws Exception { ObjectType derived = registry.createObjectType(registry.createObjectType(namedGoogBar)); assertTrue(derived.isSubtype(googBar.getInstanceType())); } public void testNamedSubtypeChain() throws Exception { List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_PROTOTYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), googBar.getPrototype(), googBar.getInstanceType(), googSubBar.getPrototype(), googSubBar.getInstanceType(), googSubSubBar.getPrototype(), googSubSubBar.getInstanceType(), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testRecordSubtypeChain() throws Exception { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("a", STRING_TYPE, null); JSType aType = builder.build(); builder = new RecordTypeBuilder(registry); builder.addProperty("a", STRING_TYPE, null); builder.addProperty("b", STRING_TYPE, null); JSType abType = builder.build(); builder = new RecordTypeBuilder(registry); builder.addProperty("a", STRING_TYPE, null); builder.addProperty("c", STRING_TYPE, null); JSType acType = builder.build(); JSType abOrAcType = registry.createUnionType(abType, acType); builder = new RecordTypeBuilder(registry); builder.addProperty("a", STRING_TYPE, null); builder.addProperty("b", STRING_TYPE, null); builder.addProperty("c", NUMBER_TYPE, null); JSType abcType = builder.build(); List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_PROTOTYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), aType, abOrAcType, abType, abcType, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testRecordAndObjectChain2() throws Exception { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("date", DATE_TYPE, null); JSType hasDateProperty = builder.build(); List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.OBJECT_TYPE), hasDateProperty, googBar.getInstanceType(), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testRecordAndObjectChain3() throws Exception { RecordTypeBuilder builder = new RecordTypeBuilder(registry); builder.addProperty("date", UNKNOWN_TYPE, null); JSType hasUnknownDateProperty = builder.build(); List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.OBJECT_TYPE), hasUnknownDateProperty, googBar.getInstanceType(), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testNullableNamedTypeChain() throws Exception { List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.createOptionalNullableType( registry.getNativeType(JSTypeNative.OBJECT_PROTOTYPE)), registry.createOptionalNullableType( registry.getNativeType(JSTypeNative.OBJECT_TYPE)), registry.createOptionalNullableType(googBar.getPrototype()), registry.createOptionalNullableType(googBar.getInstanceType()), registry.createNullableType(googSubBar.getPrototype()), registry.createNullableType(googSubBar.getInstanceType()), googSubSubBar.getPrototype(), googSubSubBar.getInstanceType(), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testEnumTypeChain() throws Exception { List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_PROTOTYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), enumType, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testFunctionSubtypeChain() throws Exception { List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_PROTOTYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), registry.getNativeType(JSTypeNative.FUNCTION_PROTOTYPE), registry.getNativeType(JSTypeNative.GREATEST_FUNCTION_TYPE), dateMethod, registry.getNativeType(JSTypeNative.LEAST_FUNCTION_TYPE), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testFunctionUnionSubtypeChain() throws Exception { List<JSType> typeChain = Lists.newArrayList( createUnionType( OBJECT_TYPE, STRING_TYPE), createUnionType( GREATEST_FUNCTION_TYPE, googBarInst, STRING_TYPE), createUnionType( STRING_TYPE, registry.createFunctionType( createUnionType(STRING_TYPE, NUMBER_TYPE)), googBarInst), createUnionType( registry.createFunctionType(NUMBER_TYPE), googSubBarInst), LEAST_FUNCTION_TYPE, NO_OBJECT_TYPE, NO_TYPE); verifySubtypeChain(typeChain); } public void testConstructorSubtypeChain() throws Exception { List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_PROTOTYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), registry.getNativeType(JSTypeNative.FUNCTION_PROTOTYPE), registry.getNativeType(JSTypeNative.FUNCTION_INSTANCE_TYPE), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testGoogBarSubtypeChain() throws Exception { List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.FUNCTION_INSTANCE_TYPE), googBar, googSubBar, googSubSubBar, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE)); verifySubtypeChain(typeChain, false); } public void testConstructorWithArgSubtypeChain() throws Exception { FunctionType googBarArgConstructor = registry.createConstructorType( "barArg", null, registry.createParameters(googBar), null, null); FunctionType googSubBarArgConstructor = registry.createConstructorType( "subBarArg", null, registry.createParameters(googSubBar), null, null); List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.FUNCTION_INSTANCE_TYPE), googBarArgConstructor, googSubBarArgConstructor, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE)); verifySubtypeChain(typeChain, false); } public void testInterfaceInstanceSubtypeChain() throws Exception { List<JSType> typeChain = Lists.newArrayList( ALL_TYPE, OBJECT_TYPE, interfaceInstType, googBar.getPrototype(), googBarInst, googSubBar.getPrototype(), googSubBarInst, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testInterfaceInheritanceSubtypeChain() throws Exception { FunctionType tempType = registry.createConstructorType("goog.TempType", null, null, null, null); tempType.setImplementedInterfaces( Lists.<ObjectType>newArrayList(subInterfaceInstType)); List<JSType> typeChain = Lists.newArrayList( ALL_TYPE, OBJECT_TYPE, interfaceInstType, subInterfaceInstType, tempType.getPrototype(), tempType.getInstanceType(), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testAnonymousObjectChain() throws Exception { List<JSType> typeChain = Lists.newArrayList( ALL_TYPE, createNullableType(OBJECT_TYPE), OBJECT_TYPE, registry.createAnonymousObjectType(null), registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testAnonymousEnumElementChain() throws Exception { ObjectType enumElemType = registry.createEnumType( "typeB", null, registry.createAnonymousObjectType(null)).getElementsType(); List<JSType> typeChain = Lists.newArrayList( ALL_TYPE, createNullableType(OBJECT_TYPE), OBJECT_TYPE, enumElemType, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain); } public void testTemplatizedArrayChain() throws Exception { JSType arrayOfNoType = createTemplatizedType( ARRAY_TYPE, NO_TYPE); JSType arrayOfString = createTemplatizedType( ARRAY_TYPE, STRING_TYPE); JSType arrayOfStringOrNumber = createTemplatizedType( ARRAY_TYPE, createUnionType(STRING_TYPE, NUMBER_TYPE)); JSType arrayOfAllType = createTemplatizedType( ARRAY_TYPE, ALL_TYPE); List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), arrayOfAllType, arrayOfStringOrNumber, arrayOfString, arrayOfNoType, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain, false); } public void testTemplatizedArrayChain2() throws Exception { JSType arrayOfNoType = createTemplatizedType( ARRAY_TYPE, NO_TYPE); JSType arrayOfNoObjectType = createTemplatizedType( ARRAY_TYPE, NO_OBJECT_TYPE); JSType arrayOfArray = createTemplatizedType( ARRAY_TYPE, ARRAY_TYPE); JSType arrayOfObject = createTemplatizedType( ARRAY_TYPE, OBJECT_TYPE); JSType arrayOfAllType = createTemplatizedType( ARRAY_TYPE, ALL_TYPE); List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), arrayOfAllType, arrayOfObject, arrayOfArray, arrayOfNoObjectType, arrayOfNoType, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain, false); } public void testTemplatizedObjectChain() throws Exception { JSType objectOfNoType = createTemplatizedType( OBJECT_TYPE, NO_TYPE); JSType objectOfString = createTemplatizedType( OBJECT_TYPE, STRING_TYPE); JSType objectOfStringOrNumber = createTemplatizedType( OBJECT_TYPE, createUnionType(STRING_TYPE, NUMBER_TYPE)); JSType objectOfAllType = createTemplatizedType( OBJECT_TYPE, ALL_TYPE); List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), objectOfAllType, objectOfStringOrNumber, objectOfString, objectOfNoType, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain, false); } public void testMixedTemplatizedTypeChain() throws Exception { JSType arrayOfNoType = createTemplatizedType( ARRAY_TYPE, NO_TYPE); JSType arrayOfString = createTemplatizedType( ARRAY_TYPE, STRING_TYPE); JSType objectOfString = createTemplatizedType( OBJECT_TYPE, STRING_TYPE); JSType objectOfStringOrNumber = createTemplatizedType( OBJECT_TYPE, createUnionType(STRING_TYPE, NUMBER_TYPE)); JSType objectOfAllType = createTemplatizedType( OBJECT_TYPE, ALL_TYPE); List<JSType> typeChain = Lists.newArrayList( registry.getNativeType(JSTypeNative.ALL_TYPE), registry.getNativeType(JSTypeNative.OBJECT_TYPE), objectOfAllType, objectOfStringOrNumber, objectOfString, arrayOfString, arrayOfNoType, registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE), registry.getNativeType(JSTypeNative.NO_TYPE)); verifySubtypeChain(typeChain, false); } public void testTemplatizedTypeSubtypes() { JSType objectOfString = createTemplatizedType( OBJECT_TYPE, STRING_TYPE); JSType arrayOfString = createTemplatizedType( ARRAY_TYPE, STRING_TYPE); JSType arrayOfNumber = createTemplatizedType( ARRAY_TYPE, NUMBER_TYPE); JSType arrayOfUnknown = createTemplatizedType( ARRAY_TYPE, UNKNOWN_TYPE); assertFalse(objectOfString.isSubtype(ARRAY_TYPE)); // TODO(johnlenz): should this be false? assertTrue(ARRAY_TYPE.isSubtype(objectOfString)); assertFalse(objectOfString.isSubtype(ARRAY_TYPE)); // TODO(johnlenz): should this be false? assertTrue(ARRAY_TYPE.isSubtype(objectOfString)); assertTrue(arrayOfString.isSubtype(ARRAY_TYPE)); assertTrue(ARRAY_TYPE.isSubtype(arrayOfString)); assertTrue(arrayOfString.isSubtype(arrayOfUnknown)); assertTrue(arrayOfUnknown.isSubtype(arrayOfString)); assertFalse(arrayOfString.isSubtype(arrayOfNumber)); assertFalse(arrayOfNumber.isSubtype(arrayOfString)); assertTrue(arrayOfNumber.isSubtype(createUnionType(arrayOfNumber, NULL_VOID))); assertFalse(createUnionType(arrayOfNumber, NULL_VOID).isSubtype(arrayOfNumber)); assertFalse(arrayOfString.isSubtype(createUnionType(arrayOfNumber, NULL_VOID))); } public void testTemplatizedTypeRelations() throws Exception { JSType objectOfString = createTemplatizedType( OBJECT_TYPE, STRING_TYPE); JSType arrayOfString = createTemplatizedType( ARRAY_TYPE, STRING_TYPE); JSType arrayOfNumber = createTemplatizedType( ARRAY_TYPE, NUMBER_TYPE); // Union and least super type cases: // // 1) alternate:Array.<string> and current:Object ==> Object // 2) alternate:Array.<string> and current:Array ==> Array // 3) alternate:Object.<string> and current:Array ==> Array|Object.<string> // 4) alternate:Object and current:Array.<string> ==> Object // 5) alternate:Array and current:Array.<string> ==> Array // 6) alternate:Array and current:Object.<string> ==> Array|Object.<string> // 7) alternate:Array.<string> and current:Array.<number> ==> Array.<?> // 8) alternate:Array.<string> and current:Array.<string> ==> Array.<string> // 9) alternate:Array.<string> and // current:Object.<string> ==> Object.<string>|Array.<string> assertTypeEquals( OBJECT_TYPE, JSType.getLeastSupertype(arrayOfString, OBJECT_TYPE)); assertTypeEquals( OBJECT_TYPE, JSType.getLeastSupertype(OBJECT_TYPE, arrayOfString)); assertTypeEquals( ARRAY_TYPE, JSType.getLeastSupertype(arrayOfString, ARRAY_TYPE)); assertTypeEquals( ARRAY_TYPE, JSType.getLeastSupertype(ARRAY_TYPE, arrayOfString)); assertEquals( "(Array|Object.<string,?>)", JSType.getLeastSupertype(objectOfString, ARRAY_TYPE).toString()); assertEquals( "(Array|Object.<string,?>)", JSType.getLeastSupertype(ARRAY_TYPE, objectOfString).toString()); assertEquals( "Array", JSType.getLeastSupertype(arrayOfString, arrayOfNumber).toString()); assertEquals( "Array", JSType.getLeastSupertype(arrayOfNumber, arrayOfString).toString()); assertTypeEquals( arrayOfString, JSType.getLeastSupertype(arrayOfString, arrayOfString)); assertEquals( "(Array.<string>|Object.<string,?>)", JSType.getLeastSupertype(objectOfString, arrayOfString).toString()); assertEquals( "(Array.<string>|Object.<string,?>)", JSType.getLeastSupertype(arrayOfString, objectOfString).toString()); assertTypeEquals( objectOfString, JSType.getGreatestSubtype(OBJECT_TYPE, objectOfString)); assertTypeEquals( objectOfString, JSType.getGreatestSubtype(objectOfString, OBJECT_TYPE)); assertTypeEquals( ARRAY_TYPE, JSType.getGreatestSubtype(objectOfString, ARRAY_TYPE)); assertTypeEquals( JSType.getGreatestSubtype(objectOfString, arrayOfString), NO_OBJECT_TYPE); assertTypeEquals( JSType.getGreatestSubtype(OBJECT_TYPE, arrayOfString), arrayOfString); } /** * Tests that the given chain of types has a total ordering defined * by the subtype relationship, with types at the top of the lattice * listed first. * * Also verifies that the infimum of any two types on the chain * is the lower type, and the supremum of any two types on the chain * is the higher type. */ public void verifySubtypeChain(List<JSType> typeChain) throws Exception { verifySubtypeChain(typeChain, true); } public void verifySubtypeChain(List<JSType> typeChain, boolean checkSubtyping) throws Exception { // Ugh. This wouldn't require so much copy-and-paste if we had a functional // programming language. for (int i = 0; i < typeChain.size(); i++) { for (int j = 0; j < typeChain.size(); j++) { JSType typeI = typeChain.get(i); JSType typeJ = typeChain.get(j); JSType namedTypeI = getNamedWrapper("TypeI", typeI); JSType namedTypeJ = getNamedWrapper("TypeJ", typeJ); JSType proxyTypeI = new ProxyObjectType(registry, typeI); JSType proxyTypeJ = new ProxyObjectType(registry, typeJ); if (i == j) { assertTrue(typeI + " should equal itself", typeI.isEquivalentTo(typeI)); assertTrue("Named " + typeI + " should equal itself", namedTypeI.isEquivalentTo(namedTypeI)); assertTrue("Proxy " + typeI + " should equal itself", proxyTypeI.isEquivalentTo(proxyTypeI)); } else { assertFalse(typeI + " should not equal " + typeJ, typeI.isEquivalentTo(typeJ)); assertFalse("Named " + typeI + " should not equal " + typeJ, namedTypeI.isEquivalentTo(namedTypeJ)); assertFalse("Proxy " + typeI + " should not equal " + typeJ, proxyTypeI.isEquivalentTo(proxyTypeJ)); } assertTrue(typeJ + " should be castable to " + typeI, typeJ.canCastTo(typeI)); assertTrue(typeJ + " should be castable to Named " + namedTypeI, typeJ.canCastTo(namedTypeI)); assertTrue(typeJ + " should be castable to Proxy " + proxyTypeI, typeJ.canCastTo(proxyTypeI)); assertTrue( "Named " + typeJ + " should be castable to " + typeI, namedTypeJ.canCastTo(typeI)); assertTrue( "Named " + typeJ + " should be castable to Named " + typeI, namedTypeJ.canCastTo(namedTypeI)); assertTrue( "Named " + typeJ + " should be castable to Proxy " + typeI, namedTypeJ.canCastTo(proxyTypeI)); assertTrue( "Proxy " + typeJ + " should be castable to " + typeI, proxyTypeJ.canCastTo(typeI)); assertTrue( "Proxy " + typeJ + " should be castable to Named " + typeI, proxyTypeJ.canCastTo(namedTypeI)); assertTrue( "Proxy " + typeJ + " should be castable to Proxy " + typeI, proxyTypeJ.canCastTo(proxyTypeI)); if (checkSubtyping) { if (i <= j) { assertTrue(typeJ + " should be a subtype of " + typeI, typeJ.isSubtype(typeI)); assertTrue( "Named " + typeJ + " should be a subtype of Named " + typeI, namedTypeJ.isSubtype(namedTypeI)); assertTrue( "Proxy " + typeJ + " should be a subtype of Proxy " + typeI, proxyTypeJ.isSubtype(proxyTypeI)); } else { assertFalse(typeJ + " should not be a subtype of " + typeI, typeJ.isSubtype(typeI)); assertFalse( "Named " + typeJ + " should not be a subtype of Named " + typeI, namedTypeJ.isSubtype(namedTypeI)); assertFalse( "Named " + typeJ + " should not be a subtype of Named " + typeI, proxyTypeJ.isSubtype(proxyTypeI)); } JSType expectedSupremum = i < j ? typeI : typeJ; JSType expectedInfimum = i > j ? typeI : typeJ; assertTypeEquals( expectedSupremum + " should be the least supertype of " + typeI + " and " + typeJ, expectedSupremum, typeI.getLeastSupertype(typeJ)); // TODO(nicksantos): Should these tests pass? //assertTypeEquals( // expectedSupremum + " should be the least supertype of Named " + // typeI + " and Named " + typeJ, // expectedSupremum, namedTypeI.getLeastSupertype(namedTypeJ)); //assertTypeEquals( // expectedSupremum + " should be the least supertype of Proxy " + // typeI + " and Proxy " + typeJ, // expectedSupremum, proxyTypeI.getLeastSupertype(proxyTypeJ)); assertTypeEquals( expectedInfimum + " should be the greatest subtype of " + typeI + " and " + typeJ, expectedInfimum, typeI.getGreatestSubtype(typeJ)); // TODO(nicksantos): Should these tests pass? //assertTypeEquals( // expectedInfimum + " should be the greatest subtype of Named " + // typeI + " and Named " + typeJ, // expectedInfimum, namedTypeI.getGreatestSubtype(namedTypeJ)); //assertTypeEquals( // expectedInfimum + " should be the greatest subtype of Proxy " + // typeI + " and Proxy " + typeJ, // expectedInfimum, proxyTypeI.getGreatestSubtype(proxyTypeJ)); } } } } JSType getNamedWrapper(String name, JSType jstype) { // Normally, there is no way to create a Named NoType alias so // avoid confusing things by doing it here.. if (!jstype.isNoType()) { NamedType namedWrapper = new NamedType( registry, name, "[testcode]", -1, -1); namedWrapper.setReferencedType(jstype); return namedWrapper; } else { return jstype; } } /** * Tests the behavior of * {@link JSType#getRestrictedTypeGivenToBooleanOutcome(boolean)}. */ @SuppressWarnings("checked") public void testRestrictedTypeGivenToBoolean() { // simple cases assertTypeEquals(BOOLEAN_TYPE, BOOLEAN_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(BOOLEAN_TYPE, BOOLEAN_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(NO_TYPE, NULL_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(NULL_TYPE, NULL_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(NUMBER_TYPE, NUMBER_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(NUMBER_TYPE, NUMBER_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(STRING_TYPE, STRING_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(STRING_TYPE, STRING_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(STRING_OBJECT_TYPE, STRING_OBJECT_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(NO_TYPE, STRING_OBJECT_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(NO_TYPE, VOID_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(VOID_TYPE, VOID_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(NO_OBJECT_TYPE, NO_OBJECT_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(NO_TYPE, NO_OBJECT_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(NO_TYPE, NO_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(NO_TYPE, NO_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(ALL_TYPE, ALL_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); assertTypeEquals(CHECKED_UNKNOWN_TYPE, UNKNOWN_TYPE.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(UNKNOWN_TYPE, UNKNOWN_TYPE.getRestrictedTypeGivenToBooleanOutcome(false)); // unions UnionType nullableStringValue = (UnionType) createNullableType(STRING_TYPE); assertTypeEquals(STRING_TYPE, nullableStringValue.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(nullableStringValue, nullableStringValue.getRestrictedTypeGivenToBooleanOutcome(false)); UnionType nullableStringObject = (UnionType) createNullableType(STRING_OBJECT_TYPE); assertTypeEquals(STRING_OBJECT_TYPE, nullableStringObject.getRestrictedTypeGivenToBooleanOutcome(true)); assertTypeEquals(NULL_TYPE, nullableStringObject.getRestrictedTypeGivenToBooleanOutcome(false)); } public void testRegisterProperty() { int i = 0; List<JSType> allObjects = Lists.newArrayList(); for (JSType type : types) { String propName = "ALF" + i++; if (type instanceof ObjectType) { ObjectType objType = (ObjectType) type; objType.defineDeclaredProperty(propName, UNKNOWN_TYPE, null); objType.defineDeclaredProperty("allHaz", UNKNOWN_TYPE, null); assertTypeEquals(type, registry.getGreatestSubtypeWithProperty(type, propName)); List<JSType> typesWithProp = Lists.newArrayList(registry.getTypesWithProperty(propName)); String message = type.toString(); assertEquals(message, 1, typesWithProp.size()); assertTypeEquals(type, typesWithProp.get(0)); assertTypeEquals(NO_TYPE, registry.getGreatestSubtypeWithProperty(type, "GRRR")); allObjects.add(type); } } assertTypeListEquals(registry.getTypesWithProperty("GRRR"), Lists.newArrayList(NO_TYPE)); assertTypeListEquals(allObjects, registry.getTypesWithProperty("allHaz")); } public void testRegisterPropertyMemoization() { ObjectType derived1 = registry.createObjectType("d1", null, namedGoogBar); ObjectType derived2 = registry.createObjectType("d2", null, namedGoogBar); derived1.defineDeclaredProperty("propz", UNKNOWN_TYPE, null); assertTypeEquals(derived1, registry.getGreatestSubtypeWithProperty(derived1, "propz")); assertTypeEquals(NO_OBJECT_TYPE, registry.getGreatestSubtypeWithProperty(derived2, "propz")); derived2.defineDeclaredProperty("propz", UNKNOWN_TYPE, null); assertTypeEquals(derived1, registry.getGreatestSubtypeWithProperty(derived1, "propz")); assertTypeEquals(derived2, registry.getGreatestSubtypeWithProperty(derived2, "propz")); } /** * Tests * {@link JSTypeRegistry#getGreatestSubtypeWithProperty(JSType, String)}. */ public void testGreatestSubtypeWithProperty() { ObjectType foo = registry.createObjectType("foo", null, OBJECT_TYPE); ObjectType bar = registry.createObjectType("bar", null, namedGoogBar); foo.defineDeclaredProperty("propz", UNKNOWN_TYPE, null); bar.defineDeclaredProperty("propz", UNKNOWN_TYPE, null); assertTypeEquals(bar, registry.getGreatestSubtypeWithProperty(namedGoogBar, "propz")); } public void testGoodSetPrototypeBasedOn() { FunctionType fun = registry.createConstructorType( "fun", null, null, null, null); fun.setPrototypeBasedOn(unresolvedNamedType); assertTrue(fun.getInstanceType().isUnknownType()); } public void testLateSetPrototypeBasedOn() { FunctionType fun = registry.createConstructorType( "fun", null, null, null, null); assertFalse(fun.getInstanceType().isUnknownType()); fun.setPrototypeBasedOn(unresolvedNamedType); assertTrue(fun.getInstanceType().isUnknownType()); } public void testGetTypeUnderEquality1() { for (JSType type : types) { testGetTypeUnderEquality(type, type, type, type); } } public void testGetTypesUnderEquality2() { // objects can be equal to numbers testGetTypeUnderEquality( NUMBER_TYPE, OBJECT_TYPE, NUMBER_TYPE, OBJECT_TYPE); } public void testGetTypesUnderEquality3() { // null == undefined testGetTypeUnderEquality( NULL_TYPE, VOID_TYPE, NULL_TYPE, VOID_TYPE); } @SuppressWarnings("checked") public void testGetTypesUnderEquality4() { // (number,string) and number/string UnionType stringNumber = (UnionType) createUnionType(NUMBER_TYPE, STRING_TYPE); testGetTypeUnderEquality( stringNumber, STRING_TYPE, stringNumber, STRING_TYPE); testGetTypeUnderEquality( stringNumber, NUMBER_TYPE, stringNumber, NUMBER_TYPE); } public void testGetTypesUnderEquality5() { // (number,null) and undefined JSType nullUndefined = createUnionType(VOID_TYPE, NULL_TYPE); testGetTypeUnderEquality( nullUndefined, NULL_TYPE, nullUndefined, NULL_TYPE); testGetTypeUnderEquality( nullUndefined, VOID_TYPE, nullUndefined, VOID_TYPE); } public void testGetTypesUnderEquality6() { // (number,undefined,null) == null JSType optNullNumber = createUnionType(VOID_TYPE, NULL_TYPE, NUMBER_TYPE); testGetTypeUnderEquality( optNullNumber, NULL_TYPE, createUnionType(NULL_TYPE, VOID_TYPE), NULL_TYPE); } private void testGetTypeUnderEquality( JSType t1, JSType t2, JSType t1Eq, JSType t2Eq) { // creating the pairs TypePair p12 = t1.getTypesUnderEquality(t2); TypePair p21 = t2.getTypesUnderEquality(t1); // t1Eq assertTypeEquals(t1Eq, p12.typeA); assertTypeEquals(t1Eq, p21.typeB); // t2Eq assertTypeEquals(t2Eq, p12.typeB); assertTypeEquals(t2Eq, p21.typeA); } @SuppressWarnings("checked") public void testGetTypesUnderInequality1() { // objects can be not equal to numbers UnionType numberObject = (UnionType) createUnionType(NUMBER_TYPE, OBJECT_TYPE); testGetTypesUnderInequality( numberObject, NUMBER_TYPE, numberObject, NUMBER_TYPE); testGetTypesUnderInequality( numberObject, OBJECT_TYPE, numberObject, OBJECT_TYPE); } @SuppressWarnings("checked") public void testGetTypesUnderInequality2() { // null == undefined UnionType nullUndefined = (UnionType) createUnionType(VOID_TYPE, NULL_TYPE); testGetTypesUnderInequality( nullUndefined, NULL_TYPE, NO_TYPE, NO_TYPE); testGetTypesUnderInequality( nullUndefined, VOID_TYPE, NO_TYPE, NO_TYPE); } @SuppressWarnings("checked") public void testGetTypesUnderInequality3() { // (number,string) UnionType stringNumber = (UnionType) createUnionType(NUMBER_TYPE, STRING_TYPE); testGetTypesUnderInequality( stringNumber, NUMBER_TYPE, stringNumber, NUMBER_TYPE); testGetTypesUnderInequality( stringNumber, STRING_TYPE, stringNumber, STRING_TYPE); } @SuppressWarnings("checked") public void testGetTypesUnderInequality4() throws Exception { // (number,undefined,null) and null UnionType nullableOptionalNumber = (UnionType) createUnionType(NULL_TYPE, VOID_TYPE, NUMBER_TYPE); testGetTypesUnderInequality( nullableOptionalNumber, NULL_TYPE, NUMBER_TYPE, NULL_TYPE); } private void testGetTypesUnderInequality( JSType t1, JSType t2, JSType t1Eq, JSType t2Eq) { // creating the pairs TypePair p12 = t1.getTypesUnderInequality(t2); TypePair p21 = t2.getTypesUnderInequality(t1); // t1Eq assertTypeEquals(t1Eq, p12.typeA); assertTypeEquals(t1Eq, p21.typeB); // t2Eq assertTypeEquals(t2Eq, p12.typeB); assertTypeEquals(t2Eq, p21.typeA); } /** * Tests the factory method * {@link JSTypeRegistry#createRecordType}. */ public void testCreateRecordType() throws Exception { Map<String, RecordProperty> properties = new HashMap<String, RecordProperty>(); properties.put("hello", new RecordProperty(NUMBER_TYPE, null)); JSType recordType = registry.createRecordType(properties); assertEquals("{hello: number}", recordType.toString()); } /** * Tests the factory method {@link JSTypeRegistry#createOptionalType(JSType)}. */ public void testCreateOptionalType() throws Exception { // number UnionType optNumber = (UnionType) registry.createOptionalType(NUMBER_TYPE); assertUnionContains(optNumber, NUMBER_TYPE); assertUnionContains(optNumber, VOID_TYPE); // union UnionType optUnion = (UnionType) registry.createOptionalType( createUnionType(STRING_OBJECT_TYPE, DATE_TYPE)); assertUnionContains(optUnion, DATE_TYPE); assertUnionContains(optUnion, STRING_OBJECT_TYPE); assertUnionContains(optUnion, VOID_TYPE); } public void assertUnionContains(UnionType union, JSType type) { assertTrue(union + " should contain " + type, union.contains(type)); } /** * Tests the factory method * {@link JSTypeRegistry#createAnonymousObjectType}}. */ public void testCreateAnonymousObjectType() throws Exception { // anonymous ObjectType anonymous = registry.createAnonymousObjectType(null); assertTypeEquals(OBJECT_TYPE, anonymous.getImplicitPrototype()); assertNull(anonymous.getReferenceName()); assertEquals("{}", anonymous.toString()); } /** * Tests the factory method * {@link JSTypeRegistry#createAnonymousObjectType}} and adds * some properties to it. */ public void testCreateAnonymousObjectType2() throws Exception { // anonymous ObjectType anonymous = registry.createAnonymousObjectType(null); anonymous.defineDeclaredProperty( "a", NUMBER_TYPE, null); anonymous.defineDeclaredProperty( "b", NUMBER_TYPE, null); anonymous.defineDeclaredProperty( "c", NUMBER_TYPE, null); anonymous.defineDeclaredProperty( "d", NUMBER_TYPE, null); anonymous.defineDeclaredProperty( "e", NUMBER_TYPE, null); anonymous.defineDeclaredProperty( "f", NUMBER_TYPE, null); assertEquals("{a: number, b: number, c: number, d: number, ...}", anonymous.toString()); } /** * Tests the factory methods * {@link JSTypeRegistry#createObjectType(ObjectType)}} and * {@link JSTypeRegistry#createObjectType(String, Node, ObjectType)}}. */ public void testCreateObjectType() throws Exception { // simple ObjectType subDate = registry.createObjectType(DATE_TYPE.getImplicitPrototype()); assertTypeEquals(DATE_TYPE.getImplicitPrototype(), subDate.getImplicitPrototype()); assertNull(subDate.getReferenceName()); assertEquals("{...}", subDate.toString()); // name, node, prototype ObjectType subError = registry.createObjectType("Foo", null, ERROR_TYPE.getImplicitPrototype()); assertTypeEquals(ERROR_TYPE.getImplicitPrototype(), subError.getImplicitPrototype()); assertEquals("Foo", subError.getReferenceName()); } /** * Tests {@code (U2U_CONSTRUCTOR,undefined) <: (U2U_CONSTRUCTOR,undefined)}. */ @SuppressWarnings("checked") public void testBug903110() throws Exception { UnionType union = (UnionType) createUnionType(U2U_CONSTRUCTOR_TYPE, VOID_TYPE); assertTrue(VOID_TYPE.isSubtype(union)); assertTrue(U2U_CONSTRUCTOR_TYPE.isSubtype(union)); assertTrue(union.isSubtype(union)); } /** * Tests {@code U2U_FUNCTION_TYPE <: U2U_CONSTRUCTOR} and * {@code U2U_FUNCTION_TYPE <: (U2U_CONSTRUCTOR,undefined)}. */ public void testBug904123() throws Exception { assertTrue(U2U_FUNCTION_TYPE.isSubtype(U2U_CONSTRUCTOR_TYPE)); assertTrue(U2U_FUNCTION_TYPE. isSubtype(createOptionalType(U2U_CONSTRUCTOR_TYPE))); } /** * Assert that a type can assign to itself. */ private void assertTypeCanAssignToItself(JSType type) { assertTrue(type.isSubtype(type)); } /** * Tests that hasOwnProperty returns true when a property is defined directly * on a class and false if the property is defined on the supertype or not at * all. */ public void testHasOwnProperty() throws Exception { ObjectType sup = registry.createObjectType(registry.createAnonymousObjectType(null)); ObjectType sub = registry.createObjectType(sup); sup.defineProperty("base", null, false, null); sub.defineProperty("sub", null, false, null); assertTrue(sup.hasProperty("base")); assertFalse(sup.hasProperty("sub")); assertTrue(sup.hasOwnProperty("base")); assertFalse(sup.hasOwnProperty("sub")); assertFalse(sup.hasOwnProperty("none")); assertTrue(sub.hasProperty("base")); assertTrue(sub.hasProperty("sub")); assertFalse(sub.hasOwnProperty("base")); assertTrue(sub.hasOwnProperty("sub")); assertFalse(sub.hasOwnProperty("none")); } public void testNamedTypeHasOwnProperty() throws Exception { namedGoogBar.getImplicitPrototype().defineProperty("base", null, false, null); namedGoogBar.defineProperty("sub", null, false, null); assertFalse(namedGoogBar.hasOwnProperty("base")); assertTrue(namedGoogBar.hasProperty("base")); assertTrue(namedGoogBar.hasOwnProperty("sub")); assertTrue(namedGoogBar.hasProperty("sub")); } public void testInterfaceHasOwnProperty() throws Exception { interfaceInstType.defineProperty("base", null, false, null); subInterfaceInstType.defineProperty("sub", null, false, null); assertTrue(interfaceInstType.hasProperty("base")); assertFalse(interfaceInstType.hasProperty("sub")); assertTrue(interfaceInstType.hasOwnProperty("base")); assertFalse(interfaceInstType.hasOwnProperty("sub")); assertFalse(interfaceInstType.hasOwnProperty("none")); assertTrue(subInterfaceInstType.hasProperty("base")); assertTrue(subInterfaceInstType.hasProperty("sub")); assertFalse(subInterfaceInstType.hasOwnProperty("base")); assertTrue(subInterfaceInstType.hasOwnProperty("sub")); assertFalse(subInterfaceInstType.hasOwnProperty("none")); } public void testGetPropertyNames() throws Exception { ObjectType sup = registry.createObjectType(registry.createAnonymousObjectType(null)); ObjectType sub = registry.createObjectType(sup); sup.defineProperty("base", null, false, null); sub.defineProperty("sub", null, false, null); assertEquals(Sets.newHashSet("isPrototypeOf", "toLocaleString", "propertyIsEnumerable", "toString", "valueOf", "hasOwnProperty", "constructor", "base", "sub"), sub.getPropertyNames()); assertEquals(Sets.newHashSet("isPrototypeOf", "toLocaleString", "propertyIsEnumerable", "toString", "valueOf", "hasOwnProperty", "constructor", "base"), sup.getPropertyNames()); assertEquals(Sets.newHashSet(), NO_OBJECT_TYPE.getPropertyNames()); } public void testGetAndSetJSDocInfoWithNamedType() throws Exception { JSDocInfo info = new JSDocInfo(); info.setDeprecated(true); assertNull(namedGoogBar.getOwnPropertyJSDocInfo("X")); namedGoogBar.setPropertyJSDocInfo("X", info); assertTrue(namedGoogBar.getOwnPropertyJSDocInfo("X").isDeprecated()); assertPropertyTypeInferred(namedGoogBar, "X"); assertTypeEquals(UNKNOWN_TYPE, namedGoogBar.getPropertyType("X")); } public void testGetAndSetJSDocInfoWithObjectTypes() throws Exception { ObjectType sup = registry.createObjectType(registry.createAnonymousObjectType(null)); ObjectType sub = registry.createObjectType(sup); JSDocInfo deprecated = new JSDocInfo(); deprecated.setDeprecated(true); JSDocInfo privateInfo = new JSDocInfo(); privateInfo.setVisibility(Visibility.PRIVATE); sup.defineProperty("X", NUMBER_TYPE, true, null); sup.setPropertyJSDocInfo("X", privateInfo); sub.defineProperty("X", NUMBER_TYPE, true, null); sub.setPropertyJSDocInfo("X", deprecated); assertFalse(sup.getOwnPropertyJSDocInfo("X").isDeprecated()); assertEquals(Visibility.PRIVATE, sup.getOwnPropertyJSDocInfo("X").getVisibility()); assertTypeEquals(NUMBER_TYPE, sup.getPropertyType("X")); assertTrue(sub.getOwnPropertyJSDocInfo("X").isDeprecated()); assertNull(sub.getOwnPropertyJSDocInfo("X").getVisibility()); assertTypeEquals(NUMBER_TYPE, sub.getPropertyType("X")); } public void testGetAndSetJSDocInfoWithNoType() throws Exception { JSDocInfo deprecated = new JSDocInfo(); deprecated.setDeprecated(true); NO_TYPE.setPropertyJSDocInfo("X", deprecated); assertNull(NO_TYPE.getOwnPropertyJSDocInfo("X")); } public void testObjectGetSubTypes() throws Exception { assertTrue( containsType( OBJECT_FUNCTION_TYPE.getSubTypes(), googBar)); assertTrue( containsType( googBar.getSubTypes(), googSubBar)); assertFalse( containsType( googBar.getSubTypes(), googSubSubBar)); assertFalse( containsType( googSubBar.getSubTypes(), googSubBar)); assertTrue( containsType( googSubBar.getSubTypes(), googSubSubBar)); } public void testImplementingType() throws Exception { assertTrue( containsType( registry.getDirectImplementors( interfaceType.getInstanceType()), googBar)); } public void testIsTemplatedType() throws Exception { assertTrue( new TemplateType(registry, "T") .hasAnyTemplateTypes()); assertFalse(ARRAY_TYPE.hasAnyTemplateTypes()); assertTrue( createTemplatizedType(ARRAY_TYPE, new TemplateType(registry, "T")) .hasAnyTemplateTypes()); assertFalse( createTemplatizedType(ARRAY_TYPE, STRING_TYPE).hasAnyTemplateTypes()); assertTrue( new FunctionBuilder(registry) .withReturnType(new TemplateType(registry, "T")) .build() .hasAnyTemplateTypes()); assertTrue( new FunctionBuilder(registry) .withTypeOfThis(new TemplateType(registry, "T")) .build() .hasAnyTemplateTypes()); assertFalse( new FunctionBuilder(registry) .withReturnType(STRING_TYPE) .build() .hasAnyTemplateTypes()); assertTrue( registry.createUnionType( NULL_TYPE, new TemplateType(registry, "T"), STRING_TYPE) .hasAnyTemplateTypes()); assertFalse( registry.createUnionType( NULL_TYPE, ARRAY_TYPE, STRING_TYPE) .hasAnyTemplateTypes()); } public void testTemplatizedType() throws Exception { FunctionType templatizedCtor = registry.createConstructorType( "TestingType", null, null, UNKNOWN_TYPE, ImmutableList.of( registry.createTemplateType("A"), registry.createTemplateType("B"))); JSType templatizedInstance = registry.createTemplatizedType( templatizedCtor.getInstanceType(), ImmutableList.of(NUMBER_TYPE, STRING_TYPE)); TemplateTypeMap ctrTypeMap = templatizedCtor.getTemplateTypeMap(); TemplateType keyA = ctrTypeMap.getTemplateTypeKeyByName("A"); assertNotNull(keyA); TemplateType keyB = ctrTypeMap.getTemplateTypeKeyByName("B"); assertNotNull(keyB); TemplateType keyC = ctrTypeMap.getTemplateTypeKeyByName("C"); assertNull(keyC); TemplateType unknownKey = registry.createTemplateType("C"); TemplateTypeMap templateTypeMap = templatizedInstance.getTemplateTypeMap(); assertTrue(templateTypeMap.hasTemplateKey(keyA)); assertTrue(templateTypeMap.hasTemplateKey(keyB)); assertFalse(templateTypeMap.hasTemplateKey(unknownKey)); assertEquals(NUMBER_TYPE, templateTypeMap.getTemplateType(keyA)); assertEquals(STRING_TYPE, templateTypeMap.getTemplateType(keyB)); assertEquals(UNKNOWN_TYPE, templateTypeMap.getTemplateType(unknownKey)); assertEquals("TestingType.<number,string>", templatizedInstance.toString()); } public void testPartiallyTemplatizedType() throws Exception { FunctionType templatizedCtor = registry.createConstructorType( "TestingType", null, null, UNKNOWN_TYPE, ImmutableList.of( registry.createTemplateType("A"), registry.createTemplateType("B"))); JSType templatizedInstance = registry.createTemplatizedType( templatizedCtor.getInstanceType(), ImmutableList.of(NUMBER_TYPE)); TemplateTypeMap ctrTypeMap = templatizedCtor.getTemplateTypeMap(); TemplateType keyA = ctrTypeMap.getTemplateTypeKeyByName("A"); assertNotNull(keyA); TemplateType keyB = ctrTypeMap.getTemplateTypeKeyByName("B"); assertNotNull(keyB); TemplateType keyC = ctrTypeMap.getTemplateTypeKeyByName("C"); assertNull(keyC); TemplateType unknownKey = registry.createTemplateType("C"); TemplateTypeMap templateTypeMap = templatizedInstance.getTemplateTypeMap(); assertTrue(templateTypeMap.hasTemplateKey(keyA)); assertTrue(templateTypeMap.hasTemplateKey(keyB)); assertFalse(templateTypeMap.hasTemplateKey(unknownKey)); assertEquals(NUMBER_TYPE, templateTypeMap.getTemplateType(keyA)); assertEquals(UNKNOWN_TYPE, templateTypeMap.getTemplateType(keyB)); assertEquals(UNKNOWN_TYPE, templateTypeMap.getTemplateType(unknownKey)); assertEquals("TestingType.<number,?>", templatizedInstance.toString()); } public void testCanCastTo() { assertTrue(ALL_TYPE.canCastTo(NULL_TYPE)); assertTrue(ALL_TYPE.canCastTo(VOID_TYPE)); assertTrue(ALL_TYPE.canCastTo(STRING_TYPE)); assertTrue(ALL_TYPE.canCastTo(NUMBER_TYPE)); assertTrue(ALL_TYPE.canCastTo(BOOLEAN_TYPE)); assertTrue(ALL_TYPE.canCastTo(OBJECT_TYPE)); assertFalse(NUMBER_TYPE.canCastTo(NULL_TYPE)); assertFalse(NUMBER_TYPE.canCastTo(VOID_TYPE)); assertFalse(NUMBER_TYPE.canCastTo(STRING_TYPE)); assertTrue(NUMBER_TYPE.canCastTo(NUMBER_TYPE)); assertFalse(NUMBER_TYPE.canCastTo(BOOLEAN_TYPE)); assertFalse(NUMBER_TYPE.canCastTo(OBJECT_TYPE)); assertFalse(STRING_TYPE.canCastTo(NULL_TYPE)); assertFalse(STRING_TYPE.canCastTo(VOID_TYPE)); assertTrue(STRING_TYPE.canCastTo(STRING_TYPE)); assertFalse(STRING_TYPE.canCastTo(NUMBER_TYPE)); assertFalse(STRING_TYPE.canCastTo(BOOLEAN_TYPE)); assertFalse(STRING_TYPE.canCastTo(OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.canCastTo(NULL_TYPE)); assertFalse(BOOLEAN_TYPE.canCastTo(VOID_TYPE)); assertFalse(BOOLEAN_TYPE.canCastTo(STRING_TYPE)); assertFalse(BOOLEAN_TYPE.canCastTo(NUMBER_TYPE)); assertTrue(BOOLEAN_TYPE.canCastTo(BOOLEAN_TYPE)); assertFalse(BOOLEAN_TYPE.canCastTo(OBJECT_TYPE)); assertFalse(OBJECT_TYPE.canCastTo(NULL_TYPE)); assertFalse(OBJECT_TYPE.canCastTo(VOID_TYPE)); assertFalse(OBJECT_TYPE.canCastTo(STRING_TYPE)); assertFalse(OBJECT_TYPE.canCastTo(NUMBER_TYPE)); assertFalse(OBJECT_TYPE.canCastTo(BOOLEAN_TYPE)); assertTrue(OBJECT_TYPE.canCastTo(OBJECT_TYPE)); assertFalse(BOOLEAN_TYPE.canCastTo(OBJECT_NUMBER_STRING)); assertFalse(OBJECT_NUMBER_STRING.canCastTo(BOOLEAN_TYPE)); assertFalse(ARRAY_TYPE.canCastTo(U2U_FUNCTION_TYPE)); assertFalse(U2U_FUNCTION_TYPE.canCastTo(ARRAY_TYPE)); assertFalse(NULL_VOID.canCastTo(ARRAY_TYPE)); assertTrue(NULL_VOID.canCastTo(createUnionType(ARRAY_TYPE, NULL_TYPE))); // We currently allow any function to be cast to any other function type assertTrue(ARRAY_FUNCTION_TYPE.canCastTo(BOOLEAN_OBJECT_FUNCTION_TYPE)); } private static boolean containsType( Iterable<? extends JSType> types, JSType type) { for (JSType alt : types) { if (alt.isEquivalentTo(type)) { return true; } } return false; } private static boolean assertTypeListEquals( Iterable<? extends JSType> typeListA, Iterable<? extends JSType> typeListB) { for (JSType alt : typeListA) { assertTrue( "List : " + typeListA + "\n" + "does not contain: " + alt, containsType(typeListA, alt)); } for (JSType alt : typeListB) { assertTrue( "List : " + typeListB + "\n" + "does not contain: " + alt, containsType(typeListB, alt)); } return false; } private ArrowType createArrowType(Node params) { return registry.createArrowType(params); } }
[ { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "checkEquivalenceHelper", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/JSType;Lcom/google/javascript/rhino/jstype/EquivalenceMethod;)Z", "line_numbers": [ "572", "573", "576", "577", "578", "579", "582", "583", "586", "587", "592", "596", "597", "601", "602", "606", "607", "611", "613", "616", "618", "622", "625", "629", "630", "635", "636", "645" ], "method_line_rate": 0.6428571428571429 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "equals", "be_test_function_signature": "(Ljava/lang/Object;)Z", "line_numbers": [ "667" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "extendTemplateTypeMap", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/TemplateTypeMap;)V", "line_numbers": [ "464", "465" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "filterNoResolvedType", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/JSType;)Lcom/google/javascript/rhino/jstype/JSType;", "line_numbers": [ "1033", "1036", "1037", "1038", "1039", "1040", "1041", "1042", "1043", "1045", "1047", "1048", "1049", "1050", "1051", "1052", "1054", "1055", "1058" ], "method_line_rate": 0.47368421052631576 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "getConcreteNominalTypeName", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/ObjectType;)Ljava/lang/String;", "line_numbers": [ "650", "651", "653", "654", "657" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "getLeastSupertype", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/JSType;)Lcom/google/javascript/rhino/jstype/JSType;", "line_numbers": [ "932", "934", "936" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "getLeastSupertype", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/JSType;Lcom/google/javascript/rhino/jstype/JSType;)Lcom/google/javascript/rhino/jstype/JSType;", "line_numbers": [ "944", "945" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "getNativeType", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/JSTypeNative;)Lcom/google/javascript/rhino/jstype/JSType;", "line_numbers": [ "122" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "getTemplateTypeMap", "be_test_function_signature": "()Lcom/google/javascript/rhino/jstype/TemplateTypeMap;", "line_numbers": [ "456" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "hasAnyTemplateTypes", "be_test_function_signature": "()Z", "line_numbers": [ "437", "438", "439", "440", "441", "444" ], "method_line_rate": 0.8333333333333334 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "hasAnyTemplateTypesInternal", "be_test_function_signature": "()Z", "line_numbers": [ "449" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "hashCode", "be_test_function_signature": "()I", "line_numbers": [ "673" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isAllType", "be_test_function_signature": "()Z", "line_numbers": [ "253" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isEmptyType", "be_test_function_signature": "()Z", "line_numbers": [ "176" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isEquivalent", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/JSType;Lcom/google/javascript/rhino/jstype/JSType;)Z", "line_numbers": [ "661" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isEquivalentTo", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/JSType;)Z", "line_numbers": [ "543" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isExemptFromTemplateTypeInvariance", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/JSType;)Z", "line_numbers": [ "1323", "1324" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isFunctionType", "be_test_function_signature": "()Z", "line_numbers": [ "334" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isNoObjectType", "be_test_function_signature": "()Z", "line_numbers": [ "172" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isNoResolvedType", "be_test_function_signature": "()Z", "line_numbers": [ "168" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isNoType", "be_test_function_signature": "()Z", "line_numbers": [ "164" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isNominalType", "be_test_function_signature": "()Z", "line_numbers": [ "488" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isRecordType", "be_test_function_signature": "()Z", "line_numbers": [ "387" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isResolved", "be_test_function_signature": "()Z", "line_numbers": [ "1383" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isSubtype", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/JSType;)Z", "line_numbers": [ "1249" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isSubtypeHelper", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/JSType;Lcom/google/javascript/rhino/jstype/JSType;)Z", "line_numbers": [ "1258", "1259", "1262", "1263", "1266", "1267", "1270", "1271", "1272", "1273", "1274", "1276", "1277", "1282", "1283", "1284", "1285", "1289", "1290", "1291", "1293", "1295", "1296", "1299", "1300", "1305", "1306", "1311", "1312", "1315" ], "method_line_rate": 0.6 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isTemplateType", "be_test_function_signature": "()Z", "line_numbers": [ "418" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isTemplatizedType", "be_test_function_signature": "()Z", "line_numbers": [ "399" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isUnionType", "be_test_function_signature": "()Z", "line_numbers": [ "265" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "isUnknownType", "be_test_function_signature": "()Z", "line_numbers": [ "257" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "resolve", "be_test_function_signature": "(Lcom/google/javascript/rhino/ErrorReporter;Lcom/google/javascript/rhino/jstype/StaticScope;)Lcom/google/javascript/rhino/jstype/JSType;", "line_numbers": [ "1357", "1360", "1361", "1363", "1365", "1366", "1367", "1368" ], "method_line_rate": 0.875 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "restrictByNotNullOrUndefined", "be_test_function_signature": "()Lcom/google/javascript/rhino/jstype/JSType;", "line_numbers": [ "1219" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "safeResolve", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/JSType;Lcom/google/javascript/rhino/ErrorReporter;Lcom/google/javascript/rhino/jstype/StaticScope;)Lcom/google/javascript/rhino/jstype/JSType;", "line_numbers": [ "1398" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "setResolvedTypeInternal", "be_test_function_signature": "(Lcom/google/javascript/rhino/jstype/JSType;)V", "line_numbers": [ "1377", "1378", "1379" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "toMaybeFunctionType", "be_test_function_signature": "()Lcom/google/javascript/rhino/jstype/FunctionType;", "line_numbers": [ "350" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "toMaybeRecordType", "be_test_function_signature": "()Lcom/google/javascript/rhino/jstype/RecordType;", "line_numbers": [ "395" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "toMaybeTemplateType", "be_test_function_signature": "()Lcom/google/javascript/rhino/jstype/TemplateType;", "line_numbers": [ "426" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "toMaybeTemplatizedType", "be_test_function_signature": "()Lcom/google/javascript/rhino/jstype/TemplatizedType;", "line_numbers": [ "407" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "toMaybeUnionType", "be_test_function_signature": "()Lcom/google/javascript/rhino/jstype/UnionType;", "line_numbers": [ "324" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "toObjectType", "be_test_function_signature": "()Lcom/google/javascript/rhino/jstype/ObjectType;", "line_numbers": [ "792" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/javascript/rhino/jstype/JSType.java", "be_test_class_name": "com.google.javascript.rhino.jstype.JSType", "be_test_function_name": "toString", "be_test_function_signature": "()Ljava/lang/String;", "line_numbers": [ "1427" ], "method_line_rate": 1 } ]
public class BoundedIteratorTest<E> extends AbstractIteratorTest<E>
@Test public void testRemoveMiddle() { List<E> testListCopy = new ArrayList<E>(testList); Iterator<E> iter = new BoundedIterator<E>(testListCopy.iterator(), 1, 5); assertTrue(iter.hasNext()); assertEquals("b", iter.next()); assertTrue(iter.hasNext()); assertEquals("c", iter.next()); 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()); assertFalse(iter.hasNext()); try { iter.next(); fail("Expected NoSuchElementException."); } catch (NoSuchElementException nsee) { /* Success case */ } }
// // Abstract Java Tested Class // package org.apache.commons.collections4.iterators; // // import java.util.Iterator; // import java.util.NoSuchElementException; // // // // public class BoundedIterator<E> implements Iterator<E> { // private final Iterator<? extends E> iterator; // private final long offset; // private final long max; // private long pos; // // public BoundedIterator(final Iterator<? extends E> iterator, final long offset, final long max); // private void init(); // @Override // public boolean hasNext(); // private boolean checkBounds(); // @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 BoundedIteratorTest<E> extends AbstractIteratorTest<E> { // private final String[] testArray = { // "a", "b", "c", "d", "e", "f", "g" // }; // private List<E> testList; // // public BoundedIteratorTest(final String testName); // @SuppressWarnings("unchecked") // @Override // public void setUp() // throws Exception; // @Override // public Iterator<E> makeEmptyIterator(); // @Override // public Iterator<E> makeObject(); // @Test // public void testBounded(); // @Test // public void testSameAsDecorated(); // @Test // public void testEmptyBounded(); // @Test // public void testNegativeOffset(); // @Test // public void testNegativeMax(); // @Test // public void testOffsetGreaterThanSize(); // @Test // public void testMaxGreaterThanSize(); // @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 `testRemoveMiddle` for the `BoundedIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test removing an element in the middle of the iterator. Verify that the * element is removed from the underlying collection. */
src/test/java/org/apache/commons/collections4/iterators/BoundedIteratorTest.java
package org.apache.commons.collections4.iterators; import java.util.Iterator; import java.util.NoSuchElementException;
public BoundedIterator(final Iterator<? extends E> iterator, final long offset, final long max); private void init(); @Override public boolean hasNext(); private boolean checkBounds(); @Override public E next(); @Override public void remove();
308
testRemoveMiddle
```java // Abstract Java Tested Class package org.apache.commons.collections4.iterators; import java.util.Iterator; import java.util.NoSuchElementException; public class BoundedIterator<E> implements Iterator<E> { private final Iterator<? extends E> iterator; private final long offset; private final long max; private long pos; public BoundedIterator(final Iterator<? extends E> iterator, final long offset, final long max); private void init(); @Override public boolean hasNext(); private boolean checkBounds(); @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 BoundedIteratorTest<E> extends AbstractIteratorTest<E> { private final String[] testArray = { "a", "b", "c", "d", "e", "f", "g" }; private List<E> testList; public BoundedIteratorTest(final String testName); @SuppressWarnings("unchecked") @Override public void setUp() throws Exception; @Override public Iterator<E> makeEmptyIterator(); @Override public Iterator<E> makeObject(); @Test public void testBounded(); @Test public void testSameAsDecorated(); @Test public void testEmptyBounded(); @Test public void testNegativeOffset(); @Test public void testNegativeMax(); @Test public void testOffsetGreaterThanSize(); @Test public void testMaxGreaterThanSize(); @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 `testRemoveMiddle` for the `BoundedIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test removing an element in the middle of the iterator. Verify that the * element is removed from the underlying collection. */
282
// // Abstract Java Tested Class // package org.apache.commons.collections4.iterators; // // import java.util.Iterator; // import java.util.NoSuchElementException; // // // // public class BoundedIterator<E> implements Iterator<E> { // private final Iterator<? extends E> iterator; // private final long offset; // private final long max; // private long pos; // // public BoundedIterator(final Iterator<? extends E> iterator, final long offset, final long max); // private void init(); // @Override // public boolean hasNext(); // private boolean checkBounds(); // @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 BoundedIteratorTest<E> extends AbstractIteratorTest<E> { // private final String[] testArray = { // "a", "b", "c", "d", "e", "f", "g" // }; // private List<E> testList; // // public BoundedIteratorTest(final String testName); // @SuppressWarnings("unchecked") // @Override // public void setUp() // throws Exception; // @Override // public Iterator<E> makeEmptyIterator(); // @Override // public Iterator<E> makeObject(); // @Test // public void testBounded(); // @Test // public void testSameAsDecorated(); // @Test // public void testEmptyBounded(); // @Test // public void testNegativeOffset(); // @Test // public void testNegativeMax(); // @Test // public void testOffsetGreaterThanSize(); // @Test // public void testMaxGreaterThanSize(); // @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 `testRemoveMiddle` for the `BoundedIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test removing an element in the middle of the iterator. Verify that the * element is removed from the underlying collection. */ @Test public void testRemoveMiddle() {
/** * Test removing an element in the middle of the iterator. Verify that the * element is removed from the underlying collection. */
28
org.apache.commons.collections4.iterators.BoundedIterator
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.collections4.iterators; import java.util.Iterator; import java.util.NoSuchElementException; public class BoundedIterator<E> implements Iterator<E> { private final Iterator<? extends E> iterator; private final long offset; private final long max; private long pos; public BoundedIterator(final Iterator<? extends E> iterator, final long offset, final long max); private void init(); @Override public boolean hasNext(); private boolean checkBounds(); @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 BoundedIteratorTest<E> extends AbstractIteratorTest<E> { private final String[] testArray = { "a", "b", "c", "d", "e", "f", "g" }; private List<E> testList; public BoundedIteratorTest(final String testName); @SuppressWarnings("unchecked") @Override public void setUp() throws Exception; @Override public Iterator<E> makeEmptyIterator(); @Override public Iterator<E> makeObject(); @Test public void testBounded(); @Test public void testSameAsDecorated(); @Test public void testEmptyBounded(); @Test public void testNegativeOffset(); @Test public void testNegativeMax(); @Test public void testOffsetGreaterThanSize(); @Test public void testMaxGreaterThanSize(); @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 `testRemoveMiddle` for the `BoundedIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test removing an element in the middle of the iterator. Verify that the * element is removed from the underlying collection. */ @Test public void testRemoveMiddle() { ```
public class BoundedIterator<E> implements Iterator<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 BoundedIteratorTest(final String testName); @SuppressWarnings("unchecked") @Override public void setUp() throws Exception; @Override public Iterator<E> makeEmptyIterator(); @Override public Iterator<E> makeObject(); @Test public void testBounded(); @Test public void testSameAsDecorated(); @Test public void testEmptyBounded(); @Test public void testNegativeOffset(); @Test public void testNegativeMax(); @Test public void testOffsetGreaterThanSize(); @Test public void testMaxGreaterThanSize(); @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();
a1be37f69603a73a6528dae3d3195dac4f8af3937af30bd2d4f5158b4c82fb05
[ "org.apache.commons.collections4.iterators.BoundedIteratorTest::testRemoveMiddle" ]
private final Iterator<? extends E> iterator; private final long offset; private final long max; private long pos;
@Test public void testRemoveMiddle()
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 BoundedIterator}. * * @version $Id$ */ public class BoundedIteratorTest<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 BoundedIteratorTest(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 BoundedIterator<E>(Collections.<E>emptyList().iterator(), 0, 10); } @Override public Iterator<E> makeObject() { return new BoundedIterator<E>(new ArrayList<E>(testList).iterator(), 1, testList.size() - 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 testBounded() { Iterator<E> iter = new BoundedIterator<E>(testList.iterator(), 2, 4); 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()); 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 and the <code>max</code> is its size, in that the BoundedIterator * should return all the same elements as its decorated iterator. */ @Test public void testSameAsDecorated() { Iterator<E> iter = new BoundedIterator<E>(testList.iterator(), 0, testList.size()); 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 a decorated iterator bounded to a <code>max</code> of 0. The * BoundedIterator should behave as if there are no more elements to return, * since it is technically an empty iterator. */ @Test public void testEmptyBounded() { Iterator<E> iter = new BoundedIterator<E>(testList.iterator(), 3, 0); 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 BoundedIterator<E>(testList.iterator(), -1, 4); fail("Expected IllegalArgumentException."); } catch (IllegalArgumentException iae) { /* Success case */ } } /** * Test the case if a negative <code>max</code> is passed to the * constructor. {@link IllegalArgumentException} is expected. */ @Test public void testNegativeMax() { try { new BoundedIterator<E>(testList.iterator(), 3, -1); fail("Expected IllegalArgumentException."); } catch (IllegalArgumentException iae) { /* Success case */ } } /** * Test the case if the <code>offset</code> passed to the constructor is * greater than the decorated iterator's size. The BoundedIterator should * behave as if there are no more elements to return. */ @Test public void testOffsetGreaterThanSize() { Iterator<E> iter = new BoundedIterator<E>(testList.iterator(), 10, 4); assertFalse(iter.hasNext()); try { iter.next(); fail("Expected NoSuchElementException."); } catch (NoSuchElementException nsee) { /* Success case */ } } /** * Test the case if the <code>max</code> passed to the constructor is * greater than the size of the decorated iterator. The last element * returned should be the same as the last element of the decorated * iterator. */ @Test public void testMaxGreaterThanSize() { Iterator<E> iter = new BoundedIterator<E>(testList.iterator(), 1, 10); 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 <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 BoundedIterator<E>(testListCopy.iterator(), 1, 5); 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 BoundedIterator<E>(testListCopy.iterator(), 1, 5); 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 BoundedIterator<E>(testListCopy.iterator(), 1, 5); assertTrue(iter.hasNext()); assertEquals("b", iter.next()); iter.remove(); assertFalse(testListCopy.contains("b")); 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()); 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 BoundedIterator<E>(testListCopy.iterator(), 1, 5); assertTrue(iter.hasNext()); assertEquals("b", iter.next()); assertTrue(iter.hasNext()); assertEquals("c", iter.next()); 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()); 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 BoundedIterator<E>(testListCopy.iterator(), 1, 5); 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()); assertFalse(iter.hasNext()); try { iter.next(); fail("Expected NoSuchElementException."); } catch (NoSuchElementException nsee) { /* Success case */ } iter.remove(); assertFalse(testListCopy.contains("f")); 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 BoundedIterator<E>(mockIterator, 1, 5); 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/BoundedIterator.java", "be_test_class_name": "org.apache.commons.collections4.iterators.BoundedIterator", "be_test_function_name": "checkBounds", "be_test_function_signature": "()Z", "line_numbers": [ "106", "107", "109" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/collections4/iterators/BoundedIterator.java", "be_test_class_name": "org.apache.commons.collections4.iterators.BoundedIterator", "be_test_function_name": "hasNext", "be_test_function_signature": "()Z", "line_numbers": [ "95", "96", "98" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/collections4/iterators/BoundedIterator.java", "be_test_class_name": "org.apache.commons.collections4.iterators.BoundedIterator", "be_test_function_name": "init", "be_test_function_signature": "()V", "line_numbers": [ "85", "86", "87", "89" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/collections4/iterators/BoundedIterator.java", "be_test_class_name": "org.apache.commons.collections4.iterators.BoundedIterator", "be_test_function_name": "next", "be_test_function_signature": "()Ljava/lang/Object;", "line_numbers": [ "114", "115", "117", "118", "119" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/collections4/iterators/BoundedIterator.java", "be_test_class_name": "org.apache.commons.collections4.iterators.BoundedIterator", "be_test_function_name": "remove", "be_test_function_signature": "()V", "line_numbers": [ "132", "133", "135", "136" ], "method_line_rate": 0.75 } ]
public class TestUnsupportedDateTimeField extends TestCase
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); }
// // 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 `testDifferentDurationReturnDifferentObjects` for the `UnsupportedDateTimeField` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * * 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 */
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();
100
testDifferentDurationReturnDifferentObjects
```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 `testDifferentDurationReturnDifferentObjects` for the `UnsupportedDateTimeField` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * * 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 */
78
// // 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 `testDifferentDurationReturnDifferentObjects` for the `UnsupportedDateTimeField` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * * 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() {
/** * * 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 */
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 `testDifferentDurationReturnDifferentObjects` for the `UnsupportedDateTimeField` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * * 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() { ```
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();
a3cbdd7d3e8562adc9665c1367376e3b0dc7a05cbf0d69cd6268eb29ac30af44
[ "org.joda.time.field.TestUnsupportedDateTimeField::testDifferentDurationReturnDifferentObjects" ]
private static final long serialVersionUID = -1934618396111902255L; private static HashMap<DateTimeFieldType, UnsupportedDateTimeField> cCache; private final DateTimeFieldType iType; private final DurationField iDurationField;
public void testDifferentDurationReturnDifferentObjects()
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": "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 SkippingIteratorTest<E> extends AbstractIteratorTest<E>
@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 */ } }
// // 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 `testRemoveCalledTwice` 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 twice without calling * <code>next()</code> in between. */
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();
185
testRemoveCalledTwice
```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 `testRemoveCalledTwice` 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 twice without calling * <code>next()</code> in between. */
171
// // 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 `testRemoveCalledTwice` 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 twice without calling * <code>next()</code> in between. */ @Test public void testRemoveCalledTwice() {
/** * Test the <code>remove()</code> method being called twice without calling * <code>next()</code> in between. */
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 `testRemoveCalledTwice` 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 twice without calling * <code>next()</code> in between. */ @Test public void testRemoveCalledTwice() { ```
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();
a76cdc042986d52dbeba76f896c065ad83c62e195782bc8e57faf6423c7050ef
[ "org.apache.commons.collections4.iterators.SkippingIteratorTest::testRemoveCalledTwice" ]
private final long offset; private long pos;
@Test public void testRemoveCalledTwice()
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.75 } ]
public class DatasetUtilitiesTests extends TestCase
public void testIterateRangeBounds4() { YIntervalSeriesCollection dataset = new YIntervalSeriesCollection(); Range r = DatasetUtilities.iterateRangeBounds(dataset); assertNull(r); YIntervalSeries s1 = new YIntervalSeries("S1"); dataset.addSeries(s1); r = DatasetUtilities.iterateRangeBounds(dataset); assertNull(r); // try a single item s1.add(1.0, 2.0, 1.5, 2.5); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.5, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); // another item s1.add(2.0, 2.0, 1.4, 2.1); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); // another empty series YIntervalSeries s2 = new YIntervalSeries("S2"); dataset.addSeries(s2); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); // an item in series 2 s2.add(1.0, 2.0, 1.9, 2.6); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.6, r.getUpperBound(), EPSILON); }
// public static Range iterateRangeBounds(XYDataset dataset, // boolean includeInterval); // public static Range iterateToFindDomainBounds(XYDataset dataset, // List visibleSeriesKeys, boolean includeInterval); // public static Range iterateToFindRangeBounds(XYDataset dataset, // List visibleSeriesKeys, Range xRange, boolean includeInterval); // public static Number findMinimumDomainValue(XYDataset dataset); // public static Number findMaximumDomainValue(XYDataset dataset); // public static Number findMinimumRangeValue(CategoryDataset dataset); // public static Number findMinimumRangeValue(XYDataset dataset); // public static Number findMaximumRangeValue(CategoryDataset dataset); // public static Number findMaximumRangeValue(XYDataset dataset); // public static Range findStackedRangeBounds(CategoryDataset dataset); // public static Range findStackedRangeBounds(CategoryDataset dataset, // double base); // public static Range findStackedRangeBounds(CategoryDataset dataset, // KeyToGroupMap map); // public static Number findMinimumStackedRangeValue(CategoryDataset dataset); // public static Number findMaximumStackedRangeValue(CategoryDataset dataset); // public static Range findStackedRangeBounds(TableXYDataset dataset); // public static Range findStackedRangeBounds(TableXYDataset dataset, // double base); // public static double calculateStackTotal(TableXYDataset dataset, int item); // public static Range findCumulativeRangeBounds(CategoryDataset dataset); // } // // // Abstract Java Test Class // package org.jfree.data.general.junit; // // import java.util.ArrayList; // import java.util.Arrays; // import java.util.Date; // import java.util.List; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.data.KeyToGroupMap; // import org.jfree.data.Range; // import org.jfree.data.category.CategoryDataset; // import org.jfree.data.category.DefaultCategoryDataset; // import org.jfree.data.category.DefaultIntervalCategoryDataset; // import org.jfree.data.function.Function2D; // import org.jfree.data.function.LineFunction2D; // import org.jfree.data.general.DatasetUtilities; // import org.jfree.data.pie.DefaultPieDataset; // import org.jfree.data.pie.PieDataset; // import org.jfree.data.statistics.BoxAndWhiskerItem; // import org.jfree.data.statistics.DefaultBoxAndWhiskerXYDataset; // import org.jfree.data.statistics.DefaultMultiValueCategoryDataset; // import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; // import org.jfree.data.statistics.MultiValueCategoryDataset; // import org.jfree.data.xy.DefaultIntervalXYDataset; // import org.jfree.data.xy.DefaultTableXYDataset; // import org.jfree.data.xy.DefaultXYDataset; // import org.jfree.data.xy.IntervalXYDataset; // import org.jfree.data.xy.TableXYDataset; // import org.jfree.data.xy.XYDataset; // import org.jfree.data.xy.XYIntervalSeries; // import org.jfree.data.xy.XYIntervalSeriesCollection; // import org.jfree.data.xy.XYSeries; // import org.jfree.data.xy.XYSeriesCollection; // import org.jfree.data.xy.YIntervalSeries; // import org.jfree.data.xy.YIntervalSeriesCollection; // // // // public class DatasetUtilitiesTests extends TestCase { // private static final double EPSILON = 0.0000000001; // // public static Test suite(); // public DatasetUtilitiesTests(String name); // public void testJava(); // public void testCalculatePieDatasetTotal(); // public void testFindDomainBounds(); // public void testFindDomainBounds2(); // public void testFindDomainBounds3(); // public void testFindDomainBounds_NaN(); // public void testIterateDomainBounds(); // public void testIterateDomainBounds_NaN(); // public void testIterateDomainBounds_NaN2(); // public void testFindRangeBounds_CategoryDataset(); // public void testFindRangeBounds(); // public void testFindRangeBounds2(); // public void testIterateRangeBounds_CategoryDataset(); // public void testIterateRangeBounds2_CategoryDataset(); // public void testIterateRangeBounds3_CategoryDataset(); // public void testIterateRangeBounds(); // public void testIterateRangeBounds2(); // public void testIterateRangeBounds3(); // public void testIterateRangeBounds4(); // public void testFindMinimumDomainValue(); // public void testFindMaximumDomainValue(); // public void testFindMinimumRangeValue(); // public void testFindMaximumRangeValue(); // public void testMinMaxRange(); // public void test803660(); // public void testCumulativeRange1(); // public void testCumulativeRange2(); // public void testCumulativeRange3(); // public void testCumulativeRange_NaN(); // public void testCreateCategoryDataset1(); // public void testCreateCategoryDataset2(); // public void testMaximumStackedRangeValue(); // public void testFindStackedRangeBounds_CategoryDataset1(); // public void testFindStackedRangeBounds_CategoryDataset2(); // public void testFindStackedRangeBounds_CategoryDataset3(); // public void testFindStackedRangeBoundsForTableXYDataset1(); // public void testFindStackedRangeBoundsForTableXYDataset2(); // public void testStackedRangeWithMap(); // public void testIsEmptyOrNullXYDataset(); // public void testLimitPieDataset(); // public void testSampleFunction2D(); // public void testFindMinimumStackedRangeValue(); // public void testFindMinimumStackedRangeValue2(); // public void testFindMaximumStackedRangeValue(); // public void testFindMaximumStackedRangeValue2(); // private CategoryDataset createCategoryDataset1(); // private CategoryDataset createCategoryDataset2(); // private XYDataset createXYDataset1(); // private TableXYDataset createTableXYDataset1(); // public void testIterateToFindRangeBounds1_XYDataset(); // public void testIterateToFindRangeBounds2_XYDataset(); // public void testIterateToFindRangeBounds_BoxAndWhiskerXYDataset(); // public void testIterateToFindRangeBounds_StatisticalCategoryDataset(); // public void testIterateToFindRangeBounds_MultiValueCategoryDataset(); // public void testIterateRangeBounds_IntervalCategoryDataset(); // public void testBug2849731(); // public void testBug2849731_2(); // public void testBug2849731_3(); // } // You are a professional Java test case writer, please create a test case named `testIterateRangeBounds4` for the `DatasetUtilities` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Some checks for the range bounds of a dataset that implements the * {@link IntervalXYDataset} interface. */
tests/org/jfree/data/general/junit/DatasetUtilitiesTests.java
package org.jfree.data.general; import org.jfree.data.pie.PieDataset; import org.jfree.data.pie.DefaultPieDataset; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.jfree.chart.util.ArrayUtilities; import org.jfree.data.DomainInfo; import org.jfree.data.KeyToGroupMap; import org.jfree.data.KeyedValues; import org.jfree.data.Range; import org.jfree.data.RangeInfo; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.CategoryRangeInfo; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.category.IntervalCategoryDataset; import org.jfree.data.function.Function2D; import org.jfree.data.statistics.BoxAndWhiskerCategoryDataset; import org.jfree.data.statistics.BoxAndWhiskerXYDataset; import org.jfree.data.statistics.MultiValueCategoryDataset; import org.jfree.data.statistics.StatisticalCategoryDataset; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.OHLCDataset; import org.jfree.data.xy.TableXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYDomainInfo; import org.jfree.data.xy.XYRangeInfo; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection;
private DatasetUtilities(); public static double calculatePieDatasetTotal(PieDataset dataset); public static PieDataset createPieDatasetForRow(CategoryDataset dataset, Comparable rowKey); public static PieDataset createPieDatasetForRow(CategoryDataset dataset, int row); public static PieDataset createPieDatasetForColumn(CategoryDataset dataset, Comparable columnKey); public static PieDataset createPieDatasetForColumn(CategoryDataset dataset, int column); public static PieDataset createConsolidatedPieDataset(PieDataset source, Comparable key, double minimumPercent); public static PieDataset createConsolidatedPieDataset(PieDataset source, Comparable key, double minimumPercent, int minItems); public static CategoryDataset createCategoryDataset(String rowKeyPrefix, String columnKeyPrefix, double[][] data); public static CategoryDataset createCategoryDataset(String rowKeyPrefix, String columnKeyPrefix, Number[][] data); public static CategoryDataset createCategoryDataset(Comparable[] rowKeys, Comparable[] columnKeys, double[][] data); public static CategoryDataset createCategoryDataset(Comparable rowKey, KeyedValues rowData); public static XYDataset sampleFunction2D(Function2D f, double start, double end, int samples, Comparable seriesKey); public static XYSeries sampleFunction2DToSeries(Function2D f, double start, double end, int samples, Comparable seriesKey); public static boolean isEmptyOrNull(PieDataset dataset); public static boolean isEmptyOrNull(CategoryDataset dataset); public static boolean isEmptyOrNull(XYDataset dataset); public static Range findDomainBounds(XYDataset dataset); public static Range findDomainBounds(XYDataset dataset, boolean includeInterval); public static Range findDomainBounds(XYDataset dataset, List visibleSeriesKeys, boolean includeInterval); public static Range iterateDomainBounds(XYDataset dataset); public static Range iterateDomainBounds(XYDataset dataset, boolean includeInterval); public static Range findRangeBounds(CategoryDataset dataset); public static Range findRangeBounds(CategoryDataset dataset, boolean includeInterval); public static Range findRangeBounds(CategoryDataset dataset, List visibleSeriesKeys, boolean includeInterval); public static Range findRangeBounds(XYDataset dataset); public static Range findRangeBounds(XYDataset dataset, boolean includeInterval); public static Range findRangeBounds(XYDataset dataset, List visibleSeriesKeys, Range xRange, boolean includeInterval); public static Range iterateCategoryRangeBounds(CategoryDataset dataset, boolean includeInterval); public static Range iterateRangeBounds(CategoryDataset dataset); public static Range iterateRangeBounds(CategoryDataset dataset, boolean includeInterval); public static Range iterateToFindRangeBounds(CategoryDataset dataset, List visibleSeriesKeys, boolean includeInterval); public static Range iterateXYRangeBounds(XYDataset dataset); public static Range iterateRangeBounds(XYDataset dataset); public static Range iterateRangeBounds(XYDataset dataset, boolean includeInterval); public static Range iterateToFindDomainBounds(XYDataset dataset, List visibleSeriesKeys, boolean includeInterval); public static Range iterateToFindRangeBounds(XYDataset dataset, List visibleSeriesKeys, Range xRange, boolean includeInterval); public static Number findMinimumDomainValue(XYDataset dataset); public static Number findMaximumDomainValue(XYDataset dataset); public static Number findMinimumRangeValue(CategoryDataset dataset); public static Number findMinimumRangeValue(XYDataset dataset); public static Number findMaximumRangeValue(CategoryDataset dataset); public static Number findMaximumRangeValue(XYDataset dataset); public static Range findStackedRangeBounds(CategoryDataset dataset); public static Range findStackedRangeBounds(CategoryDataset dataset, double base); public static Range findStackedRangeBounds(CategoryDataset dataset, KeyToGroupMap map); public static Number findMinimumStackedRangeValue(CategoryDataset dataset); public static Number findMaximumStackedRangeValue(CategoryDataset dataset); public static Range findStackedRangeBounds(TableXYDataset dataset); public static Range findStackedRangeBounds(TableXYDataset dataset, double base); public static double calculateStackTotal(TableXYDataset dataset, int item); public static Range findCumulativeRangeBounds(CategoryDataset dataset);
485
testIterateRangeBounds4
```java public static Range iterateRangeBounds(XYDataset dataset, boolean includeInterval); public static Range iterateToFindDomainBounds(XYDataset dataset, List visibleSeriesKeys, boolean includeInterval); public static Range iterateToFindRangeBounds(XYDataset dataset, List visibleSeriesKeys, Range xRange, boolean includeInterval); public static Number findMinimumDomainValue(XYDataset dataset); public static Number findMaximumDomainValue(XYDataset dataset); public static Number findMinimumRangeValue(CategoryDataset dataset); public static Number findMinimumRangeValue(XYDataset dataset); public static Number findMaximumRangeValue(CategoryDataset dataset); public static Number findMaximumRangeValue(XYDataset dataset); public static Range findStackedRangeBounds(CategoryDataset dataset); public static Range findStackedRangeBounds(CategoryDataset dataset, double base); public static Range findStackedRangeBounds(CategoryDataset dataset, KeyToGroupMap map); public static Number findMinimumStackedRangeValue(CategoryDataset dataset); public static Number findMaximumStackedRangeValue(CategoryDataset dataset); public static Range findStackedRangeBounds(TableXYDataset dataset); public static Range findStackedRangeBounds(TableXYDataset dataset, double base); public static double calculateStackTotal(TableXYDataset dataset, int item); public static Range findCumulativeRangeBounds(CategoryDataset dataset); } // Abstract Java Test Class package org.jfree.data.general.junit; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.KeyToGroupMap; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.category.DefaultIntervalCategoryDataset; import org.jfree.data.function.Function2D; import org.jfree.data.function.LineFunction2D; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.pie.DefaultPieDataset; import org.jfree.data.pie.PieDataset; import org.jfree.data.statistics.BoxAndWhiskerItem; import org.jfree.data.statistics.DefaultBoxAndWhiskerXYDataset; import org.jfree.data.statistics.DefaultMultiValueCategoryDataset; import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; import org.jfree.data.statistics.MultiValueCategoryDataset; import org.jfree.data.xy.DefaultIntervalXYDataset; import org.jfree.data.xy.DefaultTableXYDataset; import org.jfree.data.xy.DefaultXYDataset; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.TableXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYIntervalSeries; import org.jfree.data.xy.XYIntervalSeriesCollection; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.data.xy.YIntervalSeries; import org.jfree.data.xy.YIntervalSeriesCollection; public class DatasetUtilitiesTests extends TestCase { private static final double EPSILON = 0.0000000001; public static Test suite(); public DatasetUtilitiesTests(String name); public void testJava(); public void testCalculatePieDatasetTotal(); public void testFindDomainBounds(); public void testFindDomainBounds2(); public void testFindDomainBounds3(); public void testFindDomainBounds_NaN(); public void testIterateDomainBounds(); public void testIterateDomainBounds_NaN(); public void testIterateDomainBounds_NaN2(); public void testFindRangeBounds_CategoryDataset(); public void testFindRangeBounds(); public void testFindRangeBounds2(); public void testIterateRangeBounds_CategoryDataset(); public void testIterateRangeBounds2_CategoryDataset(); public void testIterateRangeBounds3_CategoryDataset(); public void testIterateRangeBounds(); public void testIterateRangeBounds2(); public void testIterateRangeBounds3(); public void testIterateRangeBounds4(); public void testFindMinimumDomainValue(); public void testFindMaximumDomainValue(); public void testFindMinimumRangeValue(); public void testFindMaximumRangeValue(); public void testMinMaxRange(); public void test803660(); public void testCumulativeRange1(); public void testCumulativeRange2(); public void testCumulativeRange3(); public void testCumulativeRange_NaN(); public void testCreateCategoryDataset1(); public void testCreateCategoryDataset2(); public void testMaximumStackedRangeValue(); public void testFindStackedRangeBounds_CategoryDataset1(); public void testFindStackedRangeBounds_CategoryDataset2(); public void testFindStackedRangeBounds_CategoryDataset3(); public void testFindStackedRangeBoundsForTableXYDataset1(); public void testFindStackedRangeBoundsForTableXYDataset2(); public void testStackedRangeWithMap(); public void testIsEmptyOrNullXYDataset(); public void testLimitPieDataset(); public void testSampleFunction2D(); public void testFindMinimumStackedRangeValue(); public void testFindMinimumStackedRangeValue2(); public void testFindMaximumStackedRangeValue(); public void testFindMaximumStackedRangeValue2(); private CategoryDataset createCategoryDataset1(); private CategoryDataset createCategoryDataset2(); private XYDataset createXYDataset1(); private TableXYDataset createTableXYDataset1(); public void testIterateToFindRangeBounds1_XYDataset(); public void testIterateToFindRangeBounds2_XYDataset(); public void testIterateToFindRangeBounds_BoxAndWhiskerXYDataset(); public void testIterateToFindRangeBounds_StatisticalCategoryDataset(); public void testIterateToFindRangeBounds_MultiValueCategoryDataset(); public void testIterateRangeBounds_IntervalCategoryDataset(); public void testBug2849731(); public void testBug2849731_2(); public void testBug2849731_3(); } ``` You are a professional Java test case writer, please create a test case named `testIterateRangeBounds4` for the `DatasetUtilities` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Some checks for the range bounds of a dataset that implements the * {@link IntervalXYDataset} interface. */
452
// public static Range iterateRangeBounds(XYDataset dataset, // boolean includeInterval); // public static Range iterateToFindDomainBounds(XYDataset dataset, // List visibleSeriesKeys, boolean includeInterval); // public static Range iterateToFindRangeBounds(XYDataset dataset, // List visibleSeriesKeys, Range xRange, boolean includeInterval); // public static Number findMinimumDomainValue(XYDataset dataset); // public static Number findMaximumDomainValue(XYDataset dataset); // public static Number findMinimumRangeValue(CategoryDataset dataset); // public static Number findMinimumRangeValue(XYDataset dataset); // public static Number findMaximumRangeValue(CategoryDataset dataset); // public static Number findMaximumRangeValue(XYDataset dataset); // public static Range findStackedRangeBounds(CategoryDataset dataset); // public static Range findStackedRangeBounds(CategoryDataset dataset, // double base); // public static Range findStackedRangeBounds(CategoryDataset dataset, // KeyToGroupMap map); // public static Number findMinimumStackedRangeValue(CategoryDataset dataset); // public static Number findMaximumStackedRangeValue(CategoryDataset dataset); // public static Range findStackedRangeBounds(TableXYDataset dataset); // public static Range findStackedRangeBounds(TableXYDataset dataset, // double base); // public static double calculateStackTotal(TableXYDataset dataset, int item); // public static Range findCumulativeRangeBounds(CategoryDataset dataset); // } // // // Abstract Java Test Class // package org.jfree.data.general.junit; // // import java.util.ArrayList; // import java.util.Arrays; // import java.util.Date; // import java.util.List; // import junit.framework.Test; // import junit.framework.TestCase; // import junit.framework.TestSuite; // import org.jfree.data.KeyToGroupMap; // import org.jfree.data.Range; // import org.jfree.data.category.CategoryDataset; // import org.jfree.data.category.DefaultCategoryDataset; // import org.jfree.data.category.DefaultIntervalCategoryDataset; // import org.jfree.data.function.Function2D; // import org.jfree.data.function.LineFunction2D; // import org.jfree.data.general.DatasetUtilities; // import org.jfree.data.pie.DefaultPieDataset; // import org.jfree.data.pie.PieDataset; // import org.jfree.data.statistics.BoxAndWhiskerItem; // import org.jfree.data.statistics.DefaultBoxAndWhiskerXYDataset; // import org.jfree.data.statistics.DefaultMultiValueCategoryDataset; // import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; // import org.jfree.data.statistics.MultiValueCategoryDataset; // import org.jfree.data.xy.DefaultIntervalXYDataset; // import org.jfree.data.xy.DefaultTableXYDataset; // import org.jfree.data.xy.DefaultXYDataset; // import org.jfree.data.xy.IntervalXYDataset; // import org.jfree.data.xy.TableXYDataset; // import org.jfree.data.xy.XYDataset; // import org.jfree.data.xy.XYIntervalSeries; // import org.jfree.data.xy.XYIntervalSeriesCollection; // import org.jfree.data.xy.XYSeries; // import org.jfree.data.xy.XYSeriesCollection; // import org.jfree.data.xy.YIntervalSeries; // import org.jfree.data.xy.YIntervalSeriesCollection; // // // // public class DatasetUtilitiesTests extends TestCase { // private static final double EPSILON = 0.0000000001; // // public static Test suite(); // public DatasetUtilitiesTests(String name); // public void testJava(); // public void testCalculatePieDatasetTotal(); // public void testFindDomainBounds(); // public void testFindDomainBounds2(); // public void testFindDomainBounds3(); // public void testFindDomainBounds_NaN(); // public void testIterateDomainBounds(); // public void testIterateDomainBounds_NaN(); // public void testIterateDomainBounds_NaN2(); // public void testFindRangeBounds_CategoryDataset(); // public void testFindRangeBounds(); // public void testFindRangeBounds2(); // public void testIterateRangeBounds_CategoryDataset(); // public void testIterateRangeBounds2_CategoryDataset(); // public void testIterateRangeBounds3_CategoryDataset(); // public void testIterateRangeBounds(); // public void testIterateRangeBounds2(); // public void testIterateRangeBounds3(); // public void testIterateRangeBounds4(); // public void testFindMinimumDomainValue(); // public void testFindMaximumDomainValue(); // public void testFindMinimumRangeValue(); // public void testFindMaximumRangeValue(); // public void testMinMaxRange(); // public void test803660(); // public void testCumulativeRange1(); // public void testCumulativeRange2(); // public void testCumulativeRange3(); // public void testCumulativeRange_NaN(); // public void testCreateCategoryDataset1(); // public void testCreateCategoryDataset2(); // public void testMaximumStackedRangeValue(); // public void testFindStackedRangeBounds_CategoryDataset1(); // public void testFindStackedRangeBounds_CategoryDataset2(); // public void testFindStackedRangeBounds_CategoryDataset3(); // public void testFindStackedRangeBoundsForTableXYDataset1(); // public void testFindStackedRangeBoundsForTableXYDataset2(); // public void testStackedRangeWithMap(); // public void testIsEmptyOrNullXYDataset(); // public void testLimitPieDataset(); // public void testSampleFunction2D(); // public void testFindMinimumStackedRangeValue(); // public void testFindMinimumStackedRangeValue2(); // public void testFindMaximumStackedRangeValue(); // public void testFindMaximumStackedRangeValue2(); // private CategoryDataset createCategoryDataset1(); // private CategoryDataset createCategoryDataset2(); // private XYDataset createXYDataset1(); // private TableXYDataset createTableXYDataset1(); // public void testIterateToFindRangeBounds1_XYDataset(); // public void testIterateToFindRangeBounds2_XYDataset(); // public void testIterateToFindRangeBounds_BoxAndWhiskerXYDataset(); // public void testIterateToFindRangeBounds_StatisticalCategoryDataset(); // public void testIterateToFindRangeBounds_MultiValueCategoryDataset(); // public void testIterateRangeBounds_IntervalCategoryDataset(); // public void testBug2849731(); // public void testBug2849731_2(); // public void testBug2849731_3(); // } // You are a professional Java test case writer, please create a test case named `testIterateRangeBounds4` for the `DatasetUtilities` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Some checks for the range bounds of a dataset that implements the * {@link IntervalXYDataset} interface. */ public void testIterateRangeBounds4() {
/** * Some checks for the range bounds of a dataset that implements the * {@link IntervalXYDataset} interface. */
1
org.jfree.data.general.DatasetUtilities
tests
```java public static Range iterateRangeBounds(XYDataset dataset, boolean includeInterval); public static Range iterateToFindDomainBounds(XYDataset dataset, List visibleSeriesKeys, boolean includeInterval); public static Range iterateToFindRangeBounds(XYDataset dataset, List visibleSeriesKeys, Range xRange, boolean includeInterval); public static Number findMinimumDomainValue(XYDataset dataset); public static Number findMaximumDomainValue(XYDataset dataset); public static Number findMinimumRangeValue(CategoryDataset dataset); public static Number findMinimumRangeValue(XYDataset dataset); public static Number findMaximumRangeValue(CategoryDataset dataset); public static Number findMaximumRangeValue(XYDataset dataset); public static Range findStackedRangeBounds(CategoryDataset dataset); public static Range findStackedRangeBounds(CategoryDataset dataset, double base); public static Range findStackedRangeBounds(CategoryDataset dataset, KeyToGroupMap map); public static Number findMinimumStackedRangeValue(CategoryDataset dataset); public static Number findMaximumStackedRangeValue(CategoryDataset dataset); public static Range findStackedRangeBounds(TableXYDataset dataset); public static Range findStackedRangeBounds(TableXYDataset dataset, double base); public static double calculateStackTotal(TableXYDataset dataset, int item); public static Range findCumulativeRangeBounds(CategoryDataset dataset); } // Abstract Java Test Class package org.jfree.data.general.junit; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.KeyToGroupMap; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.category.DefaultIntervalCategoryDataset; import org.jfree.data.function.Function2D; import org.jfree.data.function.LineFunction2D; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.pie.DefaultPieDataset; import org.jfree.data.pie.PieDataset; import org.jfree.data.statistics.BoxAndWhiskerItem; import org.jfree.data.statistics.DefaultBoxAndWhiskerXYDataset; import org.jfree.data.statistics.DefaultMultiValueCategoryDataset; import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; import org.jfree.data.statistics.MultiValueCategoryDataset; import org.jfree.data.xy.DefaultIntervalXYDataset; import org.jfree.data.xy.DefaultTableXYDataset; import org.jfree.data.xy.DefaultXYDataset; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.TableXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYIntervalSeries; import org.jfree.data.xy.XYIntervalSeriesCollection; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.data.xy.YIntervalSeries; import org.jfree.data.xy.YIntervalSeriesCollection; public class DatasetUtilitiesTests extends TestCase { private static final double EPSILON = 0.0000000001; public static Test suite(); public DatasetUtilitiesTests(String name); public void testJava(); public void testCalculatePieDatasetTotal(); public void testFindDomainBounds(); public void testFindDomainBounds2(); public void testFindDomainBounds3(); public void testFindDomainBounds_NaN(); public void testIterateDomainBounds(); public void testIterateDomainBounds_NaN(); public void testIterateDomainBounds_NaN2(); public void testFindRangeBounds_CategoryDataset(); public void testFindRangeBounds(); public void testFindRangeBounds2(); public void testIterateRangeBounds_CategoryDataset(); public void testIterateRangeBounds2_CategoryDataset(); public void testIterateRangeBounds3_CategoryDataset(); public void testIterateRangeBounds(); public void testIterateRangeBounds2(); public void testIterateRangeBounds3(); public void testIterateRangeBounds4(); public void testFindMinimumDomainValue(); public void testFindMaximumDomainValue(); public void testFindMinimumRangeValue(); public void testFindMaximumRangeValue(); public void testMinMaxRange(); public void test803660(); public void testCumulativeRange1(); public void testCumulativeRange2(); public void testCumulativeRange3(); public void testCumulativeRange_NaN(); public void testCreateCategoryDataset1(); public void testCreateCategoryDataset2(); public void testMaximumStackedRangeValue(); public void testFindStackedRangeBounds_CategoryDataset1(); public void testFindStackedRangeBounds_CategoryDataset2(); public void testFindStackedRangeBounds_CategoryDataset3(); public void testFindStackedRangeBoundsForTableXYDataset1(); public void testFindStackedRangeBoundsForTableXYDataset2(); public void testStackedRangeWithMap(); public void testIsEmptyOrNullXYDataset(); public void testLimitPieDataset(); public void testSampleFunction2D(); public void testFindMinimumStackedRangeValue(); public void testFindMinimumStackedRangeValue2(); public void testFindMaximumStackedRangeValue(); public void testFindMaximumStackedRangeValue2(); private CategoryDataset createCategoryDataset1(); private CategoryDataset createCategoryDataset2(); private XYDataset createXYDataset1(); private TableXYDataset createTableXYDataset1(); public void testIterateToFindRangeBounds1_XYDataset(); public void testIterateToFindRangeBounds2_XYDataset(); public void testIterateToFindRangeBounds_BoxAndWhiskerXYDataset(); public void testIterateToFindRangeBounds_StatisticalCategoryDataset(); public void testIterateToFindRangeBounds_MultiValueCategoryDataset(); public void testIterateRangeBounds_IntervalCategoryDataset(); public void testBug2849731(); public void testBug2849731_2(); public void testBug2849731_3(); } ``` You are a professional Java test case writer, please create a test case named `testIterateRangeBounds4` for the `DatasetUtilities` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Some checks for the range bounds of a dataset that implements the * {@link IntervalXYDataset} interface. */ public void testIterateRangeBounds4() { ```
public final class DatasetUtilities
package org.jfree.data.general.junit; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.KeyToGroupMap; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.category.DefaultIntervalCategoryDataset; import org.jfree.data.function.Function2D; import org.jfree.data.function.LineFunction2D; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.pie.DefaultPieDataset; import org.jfree.data.pie.PieDataset; import org.jfree.data.statistics.BoxAndWhiskerItem; import org.jfree.data.statistics.DefaultBoxAndWhiskerXYDataset; import org.jfree.data.statistics.DefaultMultiValueCategoryDataset; import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; import org.jfree.data.statistics.MultiValueCategoryDataset; import org.jfree.data.xy.DefaultIntervalXYDataset; import org.jfree.data.xy.DefaultTableXYDataset; import org.jfree.data.xy.DefaultXYDataset; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.TableXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYIntervalSeries; import org.jfree.data.xy.XYIntervalSeriesCollection; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.data.xy.YIntervalSeries; import org.jfree.data.xy.YIntervalSeriesCollection;
public static Test suite(); public DatasetUtilitiesTests(String name); public void testJava(); public void testCalculatePieDatasetTotal(); public void testFindDomainBounds(); public void testFindDomainBounds2(); public void testFindDomainBounds3(); public void testFindDomainBounds_NaN(); public void testIterateDomainBounds(); public void testIterateDomainBounds_NaN(); public void testIterateDomainBounds_NaN2(); public void testFindRangeBounds_CategoryDataset(); public void testFindRangeBounds(); public void testFindRangeBounds2(); public void testIterateRangeBounds_CategoryDataset(); public void testIterateRangeBounds2_CategoryDataset(); public void testIterateRangeBounds3_CategoryDataset(); public void testIterateRangeBounds(); public void testIterateRangeBounds2(); public void testIterateRangeBounds3(); public void testIterateRangeBounds4(); public void testFindMinimumDomainValue(); public void testFindMaximumDomainValue(); public void testFindMinimumRangeValue(); public void testFindMaximumRangeValue(); public void testMinMaxRange(); public void test803660(); public void testCumulativeRange1(); public void testCumulativeRange2(); public void testCumulativeRange3(); public void testCumulativeRange_NaN(); public void testCreateCategoryDataset1(); public void testCreateCategoryDataset2(); public void testMaximumStackedRangeValue(); public void testFindStackedRangeBounds_CategoryDataset1(); public void testFindStackedRangeBounds_CategoryDataset2(); public void testFindStackedRangeBounds_CategoryDataset3(); public void testFindStackedRangeBoundsForTableXYDataset1(); public void testFindStackedRangeBoundsForTableXYDataset2(); public void testStackedRangeWithMap(); public void testIsEmptyOrNullXYDataset(); public void testLimitPieDataset(); public void testSampleFunction2D(); public void testFindMinimumStackedRangeValue(); public void testFindMinimumStackedRangeValue2(); public void testFindMaximumStackedRangeValue(); public void testFindMaximumStackedRangeValue2(); private CategoryDataset createCategoryDataset1(); private CategoryDataset createCategoryDataset2(); private XYDataset createXYDataset1(); private TableXYDataset createTableXYDataset1(); public void testIterateToFindRangeBounds1_XYDataset(); public void testIterateToFindRangeBounds2_XYDataset(); public void testIterateToFindRangeBounds_BoxAndWhiskerXYDataset(); public void testIterateToFindRangeBounds_StatisticalCategoryDataset(); public void testIterateToFindRangeBounds_MultiValueCategoryDataset(); public void testIterateRangeBounds_IntervalCategoryDataset(); public void testBug2849731(); public void testBug2849731_2(); public void testBug2849731_3();
a89cb774fd9cda4a5e177b2c88113b3e67e7815eb4efef93ab5c40f781e5da4b
[ "org.jfree.data.general.junit.DatasetUtilitiesTests::testIterateRangeBounds4" ]
public void testIterateRangeBounds4()
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.] * * -------------------------- * DatasetUtilitiesTests.java * -------------------------- * (C) Copyright 2003-2009, by Object Refinery Limited and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 18-Sep-2003 : Version 1 (DG); * 23-Mar-2004 : Added test for maximumStackedRangeValue() method (DG); * 04-Oct-2004 : Eliminated NumberUtils usage (DG); * 07-Jan-2005 : Updated for method name changes (DG); * 03-Feb-2005 : Added testFindStackedRangeBounds2() method (DG); * 26-Sep-2007 : Added testIsEmptyOrNullXYDataset() method (DG); * 28-Mar-2008 : Added and renamed various tests (DG); * 08-Oct-2008 : New tests to support patch 2131001 and related * changes (DG); * 25-Mar-2009 : Added tests for new iterateToFindRangeBounds() method (DG); * 16-May-2009 : Added * testIterateToFindRangeBounds_MultiValueCategoryDataset() (DG); * 10-Sep-2009 : Added tests for bug 2849731 (DG); * */ package org.jfree.data.general.junit; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.KeyToGroupMap; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.category.DefaultIntervalCategoryDataset; import org.jfree.data.function.Function2D; import org.jfree.data.function.LineFunction2D; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.pie.DefaultPieDataset; import org.jfree.data.pie.PieDataset; import org.jfree.data.statistics.BoxAndWhiskerItem; import org.jfree.data.statistics.DefaultBoxAndWhiskerXYDataset; import org.jfree.data.statistics.DefaultMultiValueCategoryDataset; import org.jfree.data.statistics.DefaultStatisticalCategoryDataset; import org.jfree.data.statistics.MultiValueCategoryDataset; import org.jfree.data.xy.DefaultIntervalXYDataset; import org.jfree.data.xy.DefaultTableXYDataset; import org.jfree.data.xy.DefaultXYDataset; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.TableXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYIntervalSeries; import org.jfree.data.xy.XYIntervalSeriesCollection; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.data.xy.YIntervalSeries; import org.jfree.data.xy.YIntervalSeriesCollection; /** * Tests for the {@link DatasetUtilities} class. */ public class DatasetUtilitiesTests extends TestCase { private static final double EPSILON = 0.0000000001; /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(DatasetUtilitiesTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public DatasetUtilitiesTests(String name) { super(name); } /** * Some tests to verify that Java does what I think it does! */ public void testJava() { assertTrue(Double.isNaN(Math.min(1.0, Double.NaN))); assertTrue(Double.isNaN(Math.max(1.0, Double.NaN))); } /** * Some tests for the calculatePieDatasetTotal() method. */ public void testCalculatePieDatasetTotal() { DefaultPieDataset d = new DefaultPieDataset(); assertEquals(0.0, DatasetUtilities.calculatePieDatasetTotal(d), EPSILON); d.setValue("A", 1.0); assertEquals(1.0, DatasetUtilities.calculatePieDatasetTotal(d), EPSILON); d.setValue("B", 3.0); assertEquals(4.0, DatasetUtilities.calculatePieDatasetTotal(d), EPSILON); } /** * Some tests for the findDomainBounds() method. */ public void testFindDomainBounds() { XYDataset dataset = createXYDataset1(); Range r = DatasetUtilities.findDomainBounds(dataset); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(3.0, r.getUpperBound(), EPSILON); } /** * This test checks that the standard method has 'includeInterval' * defaulting to true. */ public void testFindDomainBounds2() { DefaultIntervalXYDataset dataset = new DefaultIntervalXYDataset(); double[] x1 = new double[] {1.0, 2.0, 3.0}; double[] x1Start = new double[] {0.9, 1.9, 2.9}; double[] x1End = new double[] {1.1, 2.1, 3.1}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[] y1Start = new double[] {1.09, 2.09, 3.09}; double[] y1End = new double[] {1.11, 2.11, 3.11}; double[][] data1 = new double[][] {x1, x1Start, x1End, y1, y1Start, y1End}; dataset.addSeries("S1", data1); Range r = DatasetUtilities.findDomainBounds(dataset); assertEquals(0.9, r.getLowerBound(), EPSILON); assertEquals(3.1, r.getUpperBound(), EPSILON); } /** * This test checks that when the 'includeInterval' flag is false, the * bounds come from the regular x-values. */ public void testFindDomainBounds3() { DefaultIntervalXYDataset dataset = new DefaultIntervalXYDataset(); double[] x1 = new double[] {1.0, 2.0, 3.0}; double[] x1Start = new double[] {0.9, 1.9, 2.9}; double[] x1End = new double[] {1.1, 2.1, 3.1}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[] y1Start = new double[] {1.09, 2.09, 3.09}; double[] y1End = new double[] {1.11, 2.11, 3.11}; double[][] data1 = new double[][] {x1, x1Start, x1End, y1, y1Start, y1End}; dataset.addSeries("S1", data1); Range r = DatasetUtilities.findDomainBounds(dataset, false); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(3.0, r.getUpperBound(), EPSILON); } /** * This test checks that NaN values are ignored. */ public void testFindDomainBounds_NaN() { DefaultIntervalXYDataset dataset = new DefaultIntervalXYDataset(); double[] x1 = new double[] {1.0, 2.0, Double.NaN}; double[] x1Start = new double[] {0.9, 1.9, Double.NaN}; double[] x1End = new double[] {1.1, 2.1, Double.NaN}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[] y1Start = new double[] {1.09, 2.09, 3.09}; double[] y1End = new double[] {1.11, 2.11, 3.11}; double[][] data1 = new double[][] {x1, x1Start, x1End, y1, y1Start, y1End}; dataset.addSeries("S1", data1); Range r = DatasetUtilities.findDomainBounds(dataset); assertEquals(0.9, r.getLowerBound(), EPSILON); assertEquals(2.1, r.getUpperBound(), EPSILON); r = DatasetUtilities.findDomainBounds(dataset, false); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(2.0, r.getUpperBound(), EPSILON); } /** * Some tests for the iterateDomainBounds() method. */ public void testIterateDomainBounds() { XYDataset dataset = createXYDataset1(); Range r = DatasetUtilities.iterateDomainBounds(dataset); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(3.0, r.getUpperBound(), EPSILON); } /** * Check that NaN values in the dataset are ignored. */ public void testIterateDomainBounds_NaN() { DefaultXYDataset dataset = new DefaultXYDataset(); double[] x = new double[] {1.0, 2.0, Double.NaN, 3.0}; double[] y = new double[] {9.0, 8.0, 7.0, 6.0}; dataset.addSeries("S1", new double[][] {x, y}); Range r = DatasetUtilities.iterateDomainBounds(dataset); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(3.0, r.getUpperBound(), EPSILON); } /** * Check that NaN values in the IntervalXYDataset are ignored. */ public void testIterateDomainBounds_NaN2() { DefaultIntervalXYDataset dataset = new DefaultIntervalXYDataset(); double[] x1 = new double[] {Double.NaN, 2.0, 3.0}; double[] x1Start = new double[] {0.9, Double.NaN, 2.9}; double[] x1End = new double[] {1.1, Double.NaN, 3.1}; double[] y1 = new double[] {4.0, 5.0, 6.0}; double[] y1Start = new double[] {1.09, 2.09, 3.09}; double[] y1End = new double[] {1.11, 2.11, 3.11}; double[][] data1 = new double[][] {x1, x1Start, x1End, y1, y1Start, y1End}; dataset.addSeries("S1", data1); Range r = DatasetUtilities.iterateDomainBounds(dataset, false); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(3.0, r.getUpperBound(), EPSILON); r = DatasetUtilities.iterateDomainBounds(dataset, true); assertEquals(0.9, r.getLowerBound(), EPSILON); assertEquals(3.1, r.getUpperBound(), EPSILON); } /** * Some tests for the findRangeBounds() for a CategoryDataset method. */ public void testFindRangeBounds_CategoryDataset() { CategoryDataset dataset = createCategoryDataset1(); Range r = DatasetUtilities.findRangeBounds(dataset); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(6.0, r.getUpperBound(), EPSILON); } /** * Some tests for the findRangeBounds() method on an XYDataset. */ public void testFindRangeBounds() { XYDataset dataset = createXYDataset1(); Range r = DatasetUtilities.findRangeBounds(dataset); assertEquals(100.0, r.getLowerBound(), EPSILON); assertEquals(105.0, r.getUpperBound(), EPSILON); } /** * A test for the findRangeBounds(XYDataset) method using * an IntervalXYDataset. */ public void testFindRangeBounds2() { YIntervalSeriesCollection dataset = new YIntervalSeriesCollection(); Range r = DatasetUtilities.findRangeBounds(dataset); assertNull(r); YIntervalSeries s1 = new YIntervalSeries("S1"); dataset.addSeries(s1); r = DatasetUtilities.findRangeBounds(dataset); assertNull(r); // try a single item s1.add(1.0, 2.0, 1.5, 2.5); r = DatasetUtilities.findRangeBounds(dataset); assertEquals(1.5, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); r = DatasetUtilities.findRangeBounds(dataset, false); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(2.0, r.getUpperBound(), EPSILON); // another item s1.add(2.0, 2.0, 1.4, 2.1); r = DatasetUtilities.findRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); // another empty series YIntervalSeries s2 = new YIntervalSeries("S2"); dataset.addSeries(s2); r = DatasetUtilities.findRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); // an item in series 2 s2.add(1.0, 2.0, 1.9, 2.6); r = DatasetUtilities.findRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.6, r.getUpperBound(), EPSILON); // what if we don't want the interval? r = DatasetUtilities.findRangeBounds(dataset, false); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(2.0, r.getUpperBound(), EPSILON); } /** * Some tests for the iterateRangeBounds() method. */ public void testIterateRangeBounds_CategoryDataset() { CategoryDataset dataset = createCategoryDataset1(); Range r = DatasetUtilities.iterateRangeBounds(dataset, false); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(6.0, r.getUpperBound(), EPSILON); } /** * Some checks for the iterateRangeBounds() method. */ public void testIterateRangeBounds2_CategoryDataset() { // an empty dataset should return a null range DefaultCategoryDataset dataset = new DefaultCategoryDataset(); Range r = DatasetUtilities.iterateRangeBounds(dataset, false); assertNull(r); // a dataset with a single value dataset.addValue(1.23, "R1", "C1"); r = DatasetUtilities.iterateRangeBounds(dataset, false); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); // null is ignored dataset.addValue(null, "R2", "C1"); r = DatasetUtilities.iterateRangeBounds(dataset, false); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); // a Double.NaN should be ignored dataset.addValue(Double.NaN, "R2", "C1"); r = DatasetUtilities.iterateRangeBounds(dataset, false); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); } /** * Some checks for the iterateRangeBounds() method using an * IntervalCategoryDataset. */ public void testIterateRangeBounds3_CategoryDataset() { Number[][] starts = new Double[2][3]; Number[][] ends = new Double[2][3]; starts[0][0] = new Double(1.0); starts[0][1] = new Double(2.0); starts[0][2] = new Double(3.0); starts[1][0] = new Double(11.0); starts[1][1] = new Double(12.0); starts[1][2] = new Double(13.0); ends[0][0] = new Double(4.0); ends[0][1] = new Double(5.0); ends[0][2] = new Double(6.0); ends[1][0] = new Double(16.0); ends[1][1] = new Double(15.0); ends[1][2] = new Double(14.0); DefaultIntervalCategoryDataset d = new DefaultIntervalCategoryDataset( starts, ends); Range r = DatasetUtilities.iterateRangeBounds(d, false); assertEquals(4.0, r.getLowerBound(), EPSILON); assertEquals(16.0, r.getUpperBound(), EPSILON); r = DatasetUtilities.iterateRangeBounds(d, true); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(16.0, r.getUpperBound(), EPSILON); } /** * Some tests for the iterateRangeBounds() method. */ public void testIterateRangeBounds() { XYDataset dataset = createXYDataset1(); Range r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(100.0, r.getLowerBound(), EPSILON); assertEquals(105.0, r.getUpperBound(), EPSILON); } /** * Check the range returned when a series contains a null value. */ public void testIterateRangeBounds2() { XYSeries s1 = new XYSeries("S1"); s1.add(1.0, 1.1); s1.add(2.0, null); s1.add(3.0, 3.3); XYSeriesCollection dataset = new XYSeriesCollection(s1); Range r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.1, r.getLowerBound(), EPSILON); assertEquals(3.3, r.getUpperBound(), EPSILON); } /** * Some checks for the iterateRangeBounds() method. */ public void testIterateRangeBounds3() { // an empty dataset should return a null range XYSeriesCollection dataset = new XYSeriesCollection(); Range r = DatasetUtilities.iterateRangeBounds(dataset); assertNull(r); XYSeries s1 = new XYSeries("S1"); dataset.addSeries(s1); r = DatasetUtilities.iterateRangeBounds(dataset); assertNull(r); // a dataset with a single value s1.add(1.0, 1.23); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); // null is ignored s1.add(2.0, null); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); // Double.NaN DOESN'T mess things up s1.add(3.0, Double.NaN); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.23, r.getLowerBound(), EPSILON); assertEquals(1.23, r.getUpperBound(), EPSILON); } /** * Some checks for the range bounds of a dataset that implements the * {@link IntervalXYDataset} interface. */ public void testIterateRangeBounds4() { YIntervalSeriesCollection dataset = new YIntervalSeriesCollection(); Range r = DatasetUtilities.iterateRangeBounds(dataset); assertNull(r); YIntervalSeries s1 = new YIntervalSeries("S1"); dataset.addSeries(s1); r = DatasetUtilities.iterateRangeBounds(dataset); assertNull(r); // try a single item s1.add(1.0, 2.0, 1.5, 2.5); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.5, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); // another item s1.add(2.0, 2.0, 1.4, 2.1); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); // another empty series YIntervalSeries s2 = new YIntervalSeries("S2"); dataset.addSeries(s2); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); // an item in series 2 s2.add(1.0, 2.0, 1.9, 2.6); r = DatasetUtilities.iterateRangeBounds(dataset); assertEquals(1.4, r.getLowerBound(), EPSILON); assertEquals(2.6, r.getUpperBound(), EPSILON); } /** * Some tests for the findMinimumDomainValue() method. */ public void testFindMinimumDomainValue() { XYDataset dataset = createXYDataset1(); Number minimum = DatasetUtilities.findMinimumDomainValue(dataset); assertEquals(new Double(1.0), minimum); } /** * Some tests for the findMaximumDomainValue() method. */ public void testFindMaximumDomainValue() { XYDataset dataset = createXYDataset1(); Number maximum = DatasetUtilities.findMaximumDomainValue(dataset); assertEquals(new Double(3.0), maximum); } /** * Some tests for the findMinimumRangeValue() method. */ public void testFindMinimumRangeValue() { CategoryDataset d1 = createCategoryDataset1(); Number min1 = DatasetUtilities.findMinimumRangeValue(d1); assertEquals(new Double(1.0), min1); XYDataset d2 = createXYDataset1(); Number min2 = DatasetUtilities.findMinimumRangeValue(d2); assertEquals(new Double(100.0), min2); } /** * Some tests for the findMaximumRangeValue() method. */ public void testFindMaximumRangeValue() { CategoryDataset d1 = createCategoryDataset1(); Number max1 = DatasetUtilities.findMaximumRangeValue(d1); assertEquals(new Double(6.0), max1); XYDataset dataset = createXYDataset1(); Number maximum = DatasetUtilities.findMaximumRangeValue(dataset); assertEquals(new Double(105.0), maximum); } /** * A quick test of the min and max range value methods. */ public void testMinMaxRange() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(100.0, "Series 1", "Type 1"); dataset.addValue(101.1, "Series 1", "Type 2"); Number min = DatasetUtilities.findMinimumRangeValue(dataset); assertTrue(min.doubleValue() < 100.1); Number max = DatasetUtilities.findMaximumRangeValue(dataset); assertTrue(max.doubleValue() > 101.0); } /** * A test to reproduce bug report 803660. */ public void test803660() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(100.0, "Series 1", "Type 1"); dataset.addValue(101.1, "Series 1", "Type 2"); Number n = DatasetUtilities.findMaximumRangeValue(dataset); assertTrue(n.doubleValue() > 101.0); } /** * A simple test for the cumulative range calculation. The sequence of * "cumulative" values are considered to be { 0.0, 10.0, 25.0, 18.0 } so * the range should be 0.0 -> 25.0. */ public void testCumulativeRange1() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(10.0, "Series 1", "Start"); dataset.addValue(15.0, "Series 1", "Delta 1"); dataset.addValue(-7.0, "Series 1", "Delta 2"); Range range = DatasetUtilities.findCumulativeRangeBounds(dataset); assertEquals(0.0, range.getLowerBound(), 0.00000001); assertEquals(25.0, range.getUpperBound(), 0.00000001); } /** * A further test for the cumulative range calculation. */ public void testCumulativeRange2() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(-21.4, "Series 1", "Start Value"); dataset.addValue(11.57, "Series 1", "Delta 1"); dataset.addValue(3.51, "Series 1", "Delta 2"); dataset.addValue(-12.36, "Series 1", "Delta 3"); dataset.addValue(3.39, "Series 1", "Delta 4"); dataset.addValue(38.68, "Series 1", "Delta 5"); dataset.addValue(-43.31, "Series 1", "Delta 6"); dataset.addValue(-29.59, "Series 1", "Delta 7"); dataset.addValue(35.30, "Series 1", "Delta 8"); dataset.addValue(5.0, "Series 1", "Delta 9"); Range range = DatasetUtilities.findCumulativeRangeBounds(dataset); assertEquals(-49.51, range.getLowerBound(), 0.00000001); assertEquals(23.39, range.getUpperBound(), 0.00000001); } /** * A further test for the cumulative range calculation. */ public void testCumulativeRange3() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(15.76, "Product 1", "Labour"); dataset.addValue(8.66, "Product 1", "Administration"); dataset.addValue(4.71, "Product 1", "Marketing"); dataset.addValue(3.51, "Product 1", "Distribution"); dataset.addValue(32.64, "Product 1", "Total Expense"); Range range = DatasetUtilities.findCumulativeRangeBounds(dataset); assertEquals(0.0, range.getLowerBound(), EPSILON); assertEquals(65.28, range.getUpperBound(), EPSILON); } /** * Check that the findCumulativeRangeBounds() method ignores Double.NaN * values. */ public void testCumulativeRange_NaN() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(10.0, "Series 1", "Start"); dataset.addValue(15.0, "Series 1", "Delta 1"); dataset.addValue(Double.NaN, "Series 1", "Delta 2"); Range range = DatasetUtilities.findCumulativeRangeBounds(dataset); assertEquals(0.0, range.getLowerBound(), EPSILON); assertEquals(25.0, range.getUpperBound(), EPSILON); } /** * Test the creation of a dataset from an array. */ public void testCreateCategoryDataset1() { String[] rowKeys = {"R1", "R2", "R3"}; String[] columnKeys = {"C1", "C2"}; double[][] data = new double[3][]; data[0] = new double[] {1.1, 1.2}; data[1] = new double[] {2.1, 2.2}; data[2] = new double[] {3.1, 3.2}; CategoryDataset dataset = DatasetUtilities.createCategoryDataset( rowKeys, columnKeys, data); assertTrue(dataset.getRowCount() == 3); assertTrue(dataset.getColumnCount() == 2); } /** * Test the creation of a dataset from an array. This time is should fail * because the array dimensions are around the wrong way. */ public void testCreateCategoryDataset2() { boolean pass = false; String[] rowKeys = {"R1", "R2", "R3"}; String[] columnKeys = {"C1", "C2"}; double[][] data = new double[2][]; data[0] = new double[] {1.1, 1.2, 1.3}; data[1] = new double[] {2.1, 2.2, 2.3}; CategoryDataset dataset = null; try { dataset = DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, data); } catch (IllegalArgumentException e) { pass = true; // got it! } assertTrue(pass); assertTrue(dataset == null); } /** * Test for a bug reported in the forum: * * http://www.jfree.org/phpBB2/viewtopic.php?t=7903 */ public void testMaximumStackedRangeValue() { double v1 = 24.3; double v2 = 14.2; double v3 = 33.2; double v4 = 32.4; double v5 = 26.3; double v6 = 22.6; Number answer = new Double(Math.max(v1 + v2 + v3, v4 + v5 + v6)); DefaultCategoryDataset d = new DefaultCategoryDataset(); d.addValue(v1, "Row 0", "Column 0"); d.addValue(v2, "Row 1", "Column 0"); d.addValue(v3, "Row 2", "Column 0"); d.addValue(v4, "Row 0", "Column 1"); d.addValue(v5, "Row 1", "Column 1"); d.addValue(v6, "Row 2", "Column 1"); Number max = DatasetUtilities.findMaximumStackedRangeValue(d); assertTrue(max.equals(answer)); } /** * Some checks for the findStackedRangeBounds() method. */ public void testFindStackedRangeBounds_CategoryDataset1() { CategoryDataset d1 = createCategoryDataset1(); Range r = DatasetUtilities.findStackedRangeBounds(d1); assertEquals(0.0, r.getLowerBound(), EPSILON); assertEquals(15.0, r.getUpperBound(), EPSILON); d1 = createCategoryDataset2(); r = DatasetUtilities.findStackedRangeBounds(d1); assertEquals(-2.0, r.getLowerBound(), EPSILON); assertEquals(2.0, r.getUpperBound(), EPSILON); } /** * Some checks for the findStackedRangeBounds() method. */ public void testFindStackedRangeBounds_CategoryDataset2() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); Range r = DatasetUtilities.findStackedRangeBounds(dataset); assertTrue(r == null); dataset.addValue(5.0, "R1", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, 3.0); assertEquals(3.0, r.getLowerBound(), EPSILON); assertEquals(8.0, r.getUpperBound(), EPSILON); dataset.addValue(-1.0, "R2", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, 3.0); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(8.0, r.getUpperBound(), EPSILON); dataset.addValue(null, "R3", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, 3.0); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(8.0, r.getUpperBound(), EPSILON); dataset.addValue(Double.NaN, "R4", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, 3.0); assertEquals(2.0, r.getLowerBound(), EPSILON); assertEquals(8.0, r.getUpperBound(), EPSILON); } /** * Some checks for the findStackedRangeBounds(CategoryDataset, * KeyToGroupMap) method. */ public void testFindStackedRangeBounds_CategoryDataset3() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); KeyToGroupMap map = new KeyToGroupMap("Group A"); Range r = DatasetUtilities.findStackedRangeBounds(dataset, map); assertTrue(r == null); dataset.addValue(1.0, "R1", "C1"); dataset.addValue(2.0, "R2", "C1"); dataset.addValue(3.0, "R3", "C1"); dataset.addValue(4.0, "R4", "C1"); map.mapKeyToGroup("R1", "Group A"); map.mapKeyToGroup("R2", "Group A"); map.mapKeyToGroup("R3", "Group B"); map.mapKeyToGroup("R4", "Group B"); r = DatasetUtilities.findStackedRangeBounds(dataset, map); assertEquals(0.0, r.getLowerBound(), EPSILON); assertEquals(7.0, r.getUpperBound(), EPSILON); dataset.addValue(null, "R5", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, map); assertEquals(0.0, r.getLowerBound(), EPSILON); assertEquals(7.0, r.getUpperBound(), EPSILON); dataset.addValue(Double.NaN, "R6", "C1"); r = DatasetUtilities.findStackedRangeBounds(dataset, map); assertEquals(0.0, r.getLowerBound(), EPSILON); assertEquals(7.0, r.getUpperBound(), EPSILON); } /** * Some checks for the findStackedRangeBounds() method. */ public void testFindStackedRangeBoundsForTableXYDataset1() { TableXYDataset d2 = createTableXYDataset1(); Range r = DatasetUtilities.findStackedRangeBounds(d2); assertEquals(-2.0, r.getLowerBound(), EPSILON); assertEquals(2.0, r.getUpperBound(), EPSILON); } /** * Some checks for the findStackedRangeBounds() method. */ public void testFindStackedRangeBoundsForTableXYDataset2() { DefaultTableXYDataset d = new DefaultTableXYDataset(); Range r = DatasetUtilities.findStackedRangeBounds(d); assertEquals(r, new Range(0.0, 0.0)); } /** * Tests the stacked range extent calculation. */ public void testStackedRangeWithMap() { CategoryDataset d = createCategoryDataset1(); KeyToGroupMap map = new KeyToGroupMap("G0"); map.mapKeyToGroup("R2", "G1"); Range r = DatasetUtilities.findStackedRangeBounds(d, map); assertEquals(0.0, r.getLowerBound(), EPSILON); assertEquals(9.0, r.getUpperBound(), EPSILON); } /** * Some checks for the isEmptyOrNull(XYDataset) method. */ public void testIsEmptyOrNullXYDataset() { XYSeriesCollection dataset = null; assertTrue(DatasetUtilities.isEmptyOrNull(dataset)); dataset = new XYSeriesCollection(); assertTrue(DatasetUtilities.isEmptyOrNull(dataset)); XYSeries s1 = new XYSeries("S1"); dataset.addSeries(s1); assertTrue(DatasetUtilities.isEmptyOrNull(dataset)); s1.add(1.0, 2.0); assertFalse(DatasetUtilities.isEmptyOrNull(dataset)); s1.clear(); assertTrue(DatasetUtilities.isEmptyOrNull(dataset)); } /** * Some checks for the limitPieDataset() methods. */ public void testLimitPieDataset() { // check that empty dataset is handled OK DefaultPieDataset d1 = new DefaultPieDataset(); PieDataset d2 = DatasetUtilities.createConsolidatedPieDataset(d1, "Other", 0.05); assertEquals(0, d2.getItemCount()); // check that minItem limit is observed d1.setValue("Item 1", 1.0); d1.setValue("Item 2", 49.50); d1.setValue("Item 3", 49.50); d2 = DatasetUtilities.createConsolidatedPieDataset(d1, "Other", 0.05); assertEquals(3, d2.getItemCount()); assertEquals("Item 1", d2.getKey(0)); assertEquals("Item 2", d2.getKey(1)); assertEquals("Item 3", d2.getKey(2)); // check that minItem limit is observed d1.setValue("Item 4", 1.0); d2 = DatasetUtilities.createConsolidatedPieDataset(d1, "Other", 0.05, 2); // and that simple aggregation works assertEquals(3, d2.getItemCount()); assertEquals("Item 2", d2.getKey(0)); assertEquals("Item 3", d2.getKey(1)); assertEquals("Other", d2.getKey(2)); assertEquals(new Double(2.0), d2.getValue("Other")); } /** * Some checks for the sampleFunction2D() method. */ public void testSampleFunction2D() { Function2D f = new LineFunction2D(0, 1); XYDataset dataset = DatasetUtilities.sampleFunction2D(f, 0.0, 1.0, 2, "S1"); assertEquals(1, dataset.getSeriesCount()); assertEquals("S1", dataset.getSeriesKey(0)); assertEquals(2, dataset.getItemCount(0)); assertEquals(0.0, dataset.getXValue(0, 0), EPSILON); assertEquals(0.0, dataset.getYValue(0, 0), EPSILON); assertEquals(1.0, dataset.getXValue(0, 1), EPSILON); assertEquals(1.0, dataset.getYValue(0, 1), EPSILON); } /** * A simple check for the findMinimumStackedRangeValue() method. */ public void testFindMinimumStackedRangeValue() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); // an empty dataset should return a null max Number min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertNull(min); dataset.addValue(1.0, "R1", "C1"); min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(0.0, min.doubleValue(), EPSILON); dataset.addValue(2.0, "R2", "C1"); min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(0.0, min.doubleValue(), EPSILON); dataset.addValue(-3.0, "R3", "C1"); min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(-3.0, min.doubleValue(), EPSILON); dataset.addValue(Double.NaN, "R4", "C1"); min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(-3.0, min.doubleValue(), EPSILON); } /** * A simple check for the findMaximumStackedRangeValue() method. */ public void testFindMinimumStackedRangeValue2() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(-1.0, "R1", "C1"); Number min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(-1.0, min.doubleValue(), EPSILON); dataset.addValue(-2.0, "R2", "C1"); min = DatasetUtilities.findMinimumStackedRangeValue(dataset); assertEquals(-3.0, min.doubleValue(), EPSILON); } /** * A simple check for the findMaximumStackedRangeValue() method. */ public void testFindMaximumStackedRangeValue() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); // an empty dataset should return a null max Number max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertNull(max); dataset.addValue(1.0, "R1", "C1"); max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(1.0, max.doubleValue(), EPSILON); dataset.addValue(2.0, "R2", "C1"); max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(3.0, max.doubleValue(), EPSILON); dataset.addValue(-3.0, "R3", "C1"); max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(3.0, max.doubleValue(), EPSILON); dataset.addValue(Double.NaN, "R4", "C1"); max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(3.0, max.doubleValue(), EPSILON); } /** * A simple check for the findMaximumStackedRangeValue() method. */ public void testFindMaximumStackedRangeValue2() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(-1.0, "R1", "C1"); Number max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(0.0, max.doubleValue(), EPSILON); dataset.addValue(-2.0, "R2", "C1"); max = DatasetUtilities.findMaximumStackedRangeValue(dataset); assertEquals(0.0, max.doubleValue(), EPSILON); } /** * Creates a dataset for testing. * * @return A dataset. */ private CategoryDataset createCategoryDataset1() { DefaultCategoryDataset result = new DefaultCategoryDataset(); result.addValue(1.0, "R0", "C0"); result.addValue(1.0, "R1", "C0"); result.addValue(1.0, "R2", "C0"); result.addValue(4.0, "R0", "C1"); result.addValue(5.0, "R1", "C1"); result.addValue(6.0, "R2", "C1"); return result; } /** * Creates a dataset for testing. * * @return A dataset. */ private CategoryDataset createCategoryDataset2() { DefaultCategoryDataset result = new DefaultCategoryDataset(); result.addValue(1.0, "R0", "C0"); result.addValue(-2.0, "R1", "C0"); result.addValue(2.0, "R0", "C1"); result.addValue(-1.0, "R1", "C1"); return result; } /** * Creates a dataset for testing. * * @return A dataset. */ private XYDataset createXYDataset1() { XYSeries series1 = new XYSeries("S1"); series1.add(1.0, 100.0); series1.add(2.0, 101.0); series1.add(3.0, 102.0); XYSeries series2 = new XYSeries("S2"); series2.add(1.0, 103.0); series2.add(2.0, null); series2.add(3.0, 105.0); XYSeriesCollection result = new XYSeriesCollection(); result.addSeries(series1); result.addSeries(series2); result.setIntervalWidth(0.0); return result; } /** * Creates a sample dataset for testing purposes. * * @return A sample dataset. */ private TableXYDataset createTableXYDataset1() { DefaultTableXYDataset dataset = new DefaultTableXYDataset(); XYSeries s1 = new XYSeries("Series 1", true, false); s1.add(1.0, 1.0); s1.add(2.0, 2.0); dataset.addSeries(s1); XYSeries s2 = new XYSeries("Series 2", true, false); s2.add(1.0, -2.0); s2.add(2.0, -1.0); dataset.addSeries(s2); return dataset; } /** * Some checks for the iteratorToFindRangeBounds(XYDataset...) method. */ public void testIterateToFindRangeBounds1_XYDataset() { // null dataset throws IllegalArgumentException boolean pass = false; try { DatasetUtilities.iterateToFindRangeBounds(null, new ArrayList(), new Range(0.0, 1.0), true); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); // null list throws IllegalArgumentException pass = false; try { DatasetUtilities.iterateToFindRangeBounds(new XYSeriesCollection(), null, new Range(0.0, 1.0), true); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); // null range throws IllegalArgumentException pass = false; try { DatasetUtilities.iterateToFindRangeBounds(new XYSeriesCollection(), new ArrayList(), null, true); } catch (IllegalArgumentException e) { pass = true; } assertTrue(pass); } /** * Some tests for the iterateToFindRangeBounds() method. */ public void testIterateToFindRangeBounds2_XYDataset() { List visibleSeriesKeys = new ArrayList(); Range xRange = new Range(0.0, 10.0); // empty dataset returns null XYSeriesCollection dataset = new XYSeriesCollection(); Range r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertNull(r); // add an empty series XYSeries s1 = new XYSeries("A"); dataset.addSeries(s1); visibleSeriesKeys.add("A"); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertNull(r); // check a null value s1.add(1.0, null); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertNull(r); // check a NaN s1.add(2.0, Double.NaN); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertNull(r); // check a regular value s1.add(3.0, 5.0); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 5.0), r); // check another regular value s1.add(4.0, 6.0); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 6.0), r); // add a second series XYSeries s2 = new XYSeries("B"); dataset.addSeries(s2); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 6.0), r); visibleSeriesKeys.add("B"); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 6.0), r); // add a value to the second series s2.add(5.0, 15.0); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 15.0), r); // add a value that isn't in the xRange s2.add(15.0, 150.0); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false); assertEquals(new Range(5.0, 15.0), r); r = DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, new Range(0.0, 20.0), false); assertEquals(new Range(5.0, 150.0), r); } /** * Some checks for the iterateToFindRangeBounds() method when applied to * a BoxAndWhiskerXYDataset. */ public void testIterateToFindRangeBounds_BoxAndWhiskerXYDataset() { DefaultBoxAndWhiskerXYDataset dataset = new DefaultBoxAndWhiskerXYDataset("Series 1"); List visibleSeriesKeys = new ArrayList(); visibleSeriesKeys.add("Series 1"); Range xRange = new Range(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); assertNull(DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false)); dataset.add(new Date(50L), new BoxAndWhiskerItem(5.0, 4.9, 2.0, 8.0, 1.0, 9.0, 0.0, 10.0, new ArrayList())); assertEquals(new Range(5.0, 5.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, false)); assertEquals(new Range(1.0, 9.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, true)); } /** * Some checks for the iterateToFindRangeBounds(CategoryDataset...) * method. */ public void testIterateToFindRangeBounds_StatisticalCategoryDataset() { DefaultStatisticalCategoryDataset dataset = new DefaultStatisticalCategoryDataset(); List visibleSeriesKeys = new ArrayList(); assertNull(DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, false)); dataset.add(1.0, 0.5, "R1", "C1"); visibleSeriesKeys.add("R1"); assertEquals(new Range(1.0, 1.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, false)); assertEquals(new Range(0.5, 1.5), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); } /** * Some checks for the iterateToFindRangeBounds(CategoryDataset...) method * with a {@link MultiValueCategoryDataset}. */ public void testIterateToFindRangeBounds_MultiValueCategoryDataset() { DefaultMultiValueCategoryDataset dataset = new DefaultMultiValueCategoryDataset(); List visibleSeriesKeys = new ArrayList(); assertNull(DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); List values = Arrays.asList(new Double[] {new Double(1.0)}); dataset.add(values, "R1", "C1"); visibleSeriesKeys.add("R1"); assertEquals(new Range(1.0, 1.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); values = Arrays.asList(new Double[] {new Double(2.0), new Double(3.0)}); dataset.add(values, "R1", "C2"); assertEquals(new Range(1.0, 3.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); values = Arrays.asList(new Double[] {new Double(-1.0), new Double(-2.0)}); dataset.add(values, "R2", "C1"); assertEquals(new Range(1.0, 3.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); visibleSeriesKeys.add("R2"); assertEquals(new Range(-2.0, 3.0), DatasetUtilities.iterateToFindRangeBounds(dataset, visibleSeriesKeys, true)); } /** * Some checks for the iterateRangeBounds() method when passed an * IntervalCategoryDataset. */ public void testIterateRangeBounds_IntervalCategoryDataset() {} // Defects4J: flaky method // public void testIterateRangeBounds_IntervalCategoryDataset() { // TestIntervalCategoryDataset d = new TestIntervalCategoryDataset(); // d.addItem(1.0, 2.0, 3.0, "R1", "C1"); // assertEquals(new Range(1.0, 3.0), // DatasetUtilities.iterateRangeBounds(d)); // // d = new TestIntervalCategoryDataset(); // d.addItem(2.5, 2.0, 3.0, "R1", "C1"); // assertEquals(new Range(2.0, 3.0), // DatasetUtilities.iterateRangeBounds(d)); // // d = new TestIntervalCategoryDataset(); // d.addItem(4.0, 2.0, 3.0, "R1", "C1"); // assertEquals(new Range(2.0, 4.0), // DatasetUtilities.iterateRangeBounds(d)); // // d = new TestIntervalCategoryDataset(); // d.addItem(0.0, 2.0, 3.0, "R1", "C1"); // assertEquals(new Range(2.0, 3.0), // DatasetUtilities.iterateRangeBounds(d)); // // // try some nulls // d = new TestIntervalCategoryDataset(); // d.addItem(null, null, null, "R1", "C1"); // assertNull(DatasetUtilities.iterateRangeBounds(d)); // // d = new TestIntervalCategoryDataset(); // d.addItem(1.0, 0.0, 0.0, "R1", "C1"); // assertEquals(new Range(1.0, 1.0), // DatasetUtilities.iterateRangeBounds(d)); // // d = new TestIntervalCategoryDataset(); // d.addItem(0.0, 1.0, 0.0, "R1", "C1"); // assertEquals(new Range(1.0, 1.0), // DatasetUtilities.iterateRangeBounds(d)); // // d = new TestIntervalCategoryDataset(); // d.addItem(0.0, 0.0, 1.0, "R1", "C1"); // assertEquals(new Range(1.0, 1.0), // DatasetUtilities.iterateRangeBounds(d)); // } /** * A test for bug 2849731. */ public void testBug2849731() {} // Defects4J: flaky method // public void testBug2849731() { // TestIntervalCategoryDataset d = new TestIntervalCategoryDataset(); // d.addItem(2.5, 2.0, 3.0, "R1", "C1"); // d.addItem(4.0, 0.0, 0.0, "R2", "C1"); // assertEquals(new Range(2.0, 4.0), // DatasetUtilities.iterateRangeBounds(d)); // } /** * Another test for bug 2849731. */ public void testBug2849731_2() { XYIntervalSeriesCollection d = new XYIntervalSeriesCollection(); XYIntervalSeries s = new XYIntervalSeries("S1"); s.add(1.0, Double.NaN, Double.NaN, Double.NaN, 1.5, Double.NaN); d.addSeries(s); Range r = DatasetUtilities.iterateDomainBounds(d); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(1.0, r.getUpperBound(), EPSILON); s.add(1.0, 1.5, Double.NaN, Double.NaN, 1.5, Double.NaN); r = DatasetUtilities.iterateDomainBounds(d); assertEquals(1.0, r.getLowerBound(), EPSILON); assertEquals(1.5, r.getUpperBound(), EPSILON); s.add(1.0, Double.NaN, 0.5, Double.NaN, 1.5, Double.NaN); r = DatasetUtilities.iterateDomainBounds(d); assertEquals(0.5, r.getLowerBound(), EPSILON); assertEquals(1.5, r.getUpperBound(), EPSILON); } /** * Yet another test for bug 2849731. */ public void testBug2849731_3() { XYIntervalSeriesCollection d = new XYIntervalSeriesCollection(); XYIntervalSeries s = new XYIntervalSeries("S1"); s.add(1.0, Double.NaN, Double.NaN, 1.5, Double.NaN, Double.NaN); d.addSeries(s); Range r = DatasetUtilities.iterateRangeBounds(d); assertEquals(1.5, r.getLowerBound(), EPSILON); assertEquals(1.5, r.getUpperBound(), EPSILON); s.add(1.0, 1.5, Double.NaN, Double.NaN, Double.NaN, 2.5); r = DatasetUtilities.iterateRangeBounds(d); assertEquals(1.5, r.getLowerBound(), EPSILON); assertEquals(2.5, r.getUpperBound(), EPSILON); s.add(1.0, Double.NaN, 0.5, Double.NaN, 3.5, Double.NaN); r = DatasetUtilities.iterateRangeBounds(d); assertEquals(1.5, r.getLowerBound(), EPSILON); assertEquals(3.5, r.getUpperBound(), EPSILON); } }
[ { "be_test_class_file": "org/jfree/data/general/DatasetUtilities.java", "be_test_class_name": "org.jfree.data.general.DatasetUtilities", "be_test_function_name": "iterateRangeBounds", "be_test_function_signature": "(Lorg/jfree/data/xy/XYDataset;)Lorg/jfree/data/Range;", "line_numbers": [ "1220" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/general/DatasetUtilities.java", "be_test_class_name": "org.jfree.data.general.DatasetUtilities", "be_test_function_name": "iterateRangeBounds", "be_test_function_signature": "(Lorg/jfree/data/xy/XYDataset;Z)Lorg/jfree/data/Range;", "line_numbers": [ "1238", "1239", "1240", "1243", "1245", "1246", "1247", "1248", "1249", "1250", "1251", "1252", "1253", "1254", "1256", "1257", "1258", "1260", "1261", "1262", "1266", "1267", "1269", "1270", "1271", "1272", "1273", "1274", "1275", "1276", "1278", "1279", "1283", "1286", "1287", "1288", "1289", "1290", "1291", "1292", "1297", "1298", "1301" ], "method_line_rate": 0.5581395348837209 } ]
public class AggregateSummaryStatisticsTest
@Test public void testAggregate() { // Generate a random sample and random partition double[] totalSample = generateSample(); double[][] subSamples = generatePartition(totalSample); int nSamples = subSamples.length; // Compute combined stats directly SummaryStatistics totalStats = new SummaryStatistics(); for (int i = 0; i < totalSample.length; i++) { totalStats.addValue(totalSample[i]); } // Now compute subsample stats individually and aggregate SummaryStatistics[] subSampleStats = new SummaryStatistics[nSamples]; for (int i = 0; i < nSamples; i++) { subSampleStats[i] = new SummaryStatistics(); } Collection<SummaryStatistics> aggregate = new ArrayList<SummaryStatistics>(); for (int i = 0; i < nSamples; i++) { for (int j = 0; j < subSamples[i].length; j++) { subSampleStats[i].addValue(subSamples[i][j]); } aggregate.add(subSampleStats[i]); } // Compare values StatisticalSummary aggregatedStats = AggregateSummaryStatistics.aggregate(aggregate); assertEquals(totalStats.getSummary(), aggregatedStats, 10E-12); }
// // Abstract Java Tested Class // package org.apache.commons.math3.stat.descriptive; // // import java.io.Serializable; // import java.util.Collection; // import java.util.Iterator; // import org.apache.commons.math3.exception.NullArgumentException; // // // // public class AggregateSummaryStatistics implements StatisticalSummary, // Serializable { // private static final long serialVersionUID = -8207112444016386906L; // private final SummaryStatistics statisticsPrototype; // private final SummaryStatistics statistics; // // public AggregateSummaryStatistics(); // public AggregateSummaryStatistics(SummaryStatistics prototypeStatistics) throws NullArgumentException; // public AggregateSummaryStatistics(SummaryStatistics prototypeStatistics, // SummaryStatistics initialStatistics); // public double getMax(); // public double getMean(); // public double getMin(); // public long getN(); // public double getStandardDeviation(); // public double getSum(); // public double getVariance(); // public double getSumOfLogs(); // public double getGeometricMean(); // public double getSumsq(); // public double getSecondMoment(); // public StatisticalSummary getSummary(); // public SummaryStatistics createContributingStatistics(); // public static StatisticalSummaryValues aggregate(Collection<SummaryStatistics> statistics); // public AggregatingSummaryStatistics(SummaryStatistics aggregateStatistics); // @Override // public void addValue(double value); // @Override // public boolean equals(Object object); // @Override // public int hashCode(); // } // // // Abstract Java Test Class // package org.apache.commons.math3.stat.descriptive; // // import java.util.ArrayList; // import java.util.Collection; // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.distribution.RealDistribution; // import org.apache.commons.math3.distribution.UniformRealDistribution; // import org.apache.commons.math3.distribution.IntegerDistribution; // import org.apache.commons.math3.distribution.UniformIntegerDistribution; // import org.apache.commons.math3.util.Precision; // import org.junit.Assert; // import org.junit.Test; // // // // public class AggregateSummaryStatisticsTest { // // // @Test // public void testAggregation(); // @Test // public void testAggregationConsistency(); // @Test // public void testAggregate(); // @Test // public void testAggregateDegenerate(); // @Test // public void testAggregateSpecialValues(); // protected static void assertEquals(StatisticalSummary expected, StatisticalSummary observed, double delta); // private double[] generateSample(); // private double[][] generatePartition(double[] sample); // } // You are a professional Java test case writer, please create a test case named `testAggregate` for the `AggregateSummaryStatistics` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test aggregate function by randomly generating a dataset of 10-100 values * from [-100, 100], dividing it into 2-5 partitions, computing stats for each * partition and comparing the result of aggregate(...) applied to the collection * of per-partition SummaryStatistics with a single SummaryStatistics computed * over the full sample. * */
src/test/java/org/apache/commons/math3/stat/descriptive/AggregateSummaryStatisticsTest.java
package org.apache.commons.math3.stat.descriptive; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import org.apache.commons.math3.exception.NullArgumentException;
public AggregateSummaryStatistics(); public AggregateSummaryStatistics(SummaryStatistics prototypeStatistics) throws NullArgumentException; public AggregateSummaryStatistics(SummaryStatistics prototypeStatistics, SummaryStatistics initialStatistics); public double getMax(); public double getMean(); public double getMin(); public long getN(); public double getStandardDeviation(); public double getSum(); public double getVariance(); public double getSumOfLogs(); public double getGeometricMean(); public double getSumsq(); public double getSecondMoment(); public StatisticalSummary getSummary(); public SummaryStatistics createContributingStatistics(); public static StatisticalSummaryValues aggregate(Collection<SummaryStatistics> statistics); public AggregatingSummaryStatistics(SummaryStatistics aggregateStatistics); @Override public void addValue(double value); @Override public boolean equals(Object object); @Override public int hashCode();
163
testAggregate
```java // Abstract Java Tested Class package org.apache.commons.math3.stat.descriptive; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import org.apache.commons.math3.exception.NullArgumentException; public class AggregateSummaryStatistics implements StatisticalSummary, Serializable { private static final long serialVersionUID = -8207112444016386906L; private final SummaryStatistics statisticsPrototype; private final SummaryStatistics statistics; public AggregateSummaryStatistics(); public AggregateSummaryStatistics(SummaryStatistics prototypeStatistics) throws NullArgumentException; public AggregateSummaryStatistics(SummaryStatistics prototypeStatistics, SummaryStatistics initialStatistics); public double getMax(); public double getMean(); public double getMin(); public long getN(); public double getStandardDeviation(); public double getSum(); public double getVariance(); public double getSumOfLogs(); public double getGeometricMean(); public double getSumsq(); public double getSecondMoment(); public StatisticalSummary getSummary(); public SummaryStatistics createContributingStatistics(); public static StatisticalSummaryValues aggregate(Collection<SummaryStatistics> statistics); public AggregatingSummaryStatistics(SummaryStatistics aggregateStatistics); @Override public void addValue(double value); @Override public boolean equals(Object object); @Override public int hashCode(); } // Abstract Java Test Class package org.apache.commons.math3.stat.descriptive; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.distribution.RealDistribution; import org.apache.commons.math3.distribution.UniformRealDistribution; import org.apache.commons.math3.distribution.IntegerDistribution; import org.apache.commons.math3.distribution.UniformIntegerDistribution; import org.apache.commons.math3.util.Precision; import org.junit.Assert; import org.junit.Test; public class AggregateSummaryStatisticsTest { @Test public void testAggregation(); @Test public void testAggregationConsistency(); @Test public void testAggregate(); @Test public void testAggregateDegenerate(); @Test public void testAggregateSpecialValues(); protected static void assertEquals(StatisticalSummary expected, StatisticalSummary observed, double delta); private double[] generateSample(); private double[][] generatePartition(double[] sample); } ``` You are a professional Java test case writer, please create a test case named `testAggregate` for the `AggregateSummaryStatistics` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test aggregate function by randomly generating a dataset of 10-100 values * from [-100, 100], dividing it into 2-5 partitions, computing stats for each * partition and comparing the result of aggregate(...) applied to the collection * of per-partition SummaryStatistics with a single SummaryStatistics computed * over the full sample. * */
133
// // Abstract Java Tested Class // package org.apache.commons.math3.stat.descriptive; // // import java.io.Serializable; // import java.util.Collection; // import java.util.Iterator; // import org.apache.commons.math3.exception.NullArgumentException; // // // // public class AggregateSummaryStatistics implements StatisticalSummary, // Serializable { // private static final long serialVersionUID = -8207112444016386906L; // private final SummaryStatistics statisticsPrototype; // private final SummaryStatistics statistics; // // public AggregateSummaryStatistics(); // public AggregateSummaryStatistics(SummaryStatistics prototypeStatistics) throws NullArgumentException; // public AggregateSummaryStatistics(SummaryStatistics prototypeStatistics, // SummaryStatistics initialStatistics); // public double getMax(); // public double getMean(); // public double getMin(); // public long getN(); // public double getStandardDeviation(); // public double getSum(); // public double getVariance(); // public double getSumOfLogs(); // public double getGeometricMean(); // public double getSumsq(); // public double getSecondMoment(); // public StatisticalSummary getSummary(); // public SummaryStatistics createContributingStatistics(); // public static StatisticalSummaryValues aggregate(Collection<SummaryStatistics> statistics); // public AggregatingSummaryStatistics(SummaryStatistics aggregateStatistics); // @Override // public void addValue(double value); // @Override // public boolean equals(Object object); // @Override // public int hashCode(); // } // // // Abstract Java Test Class // package org.apache.commons.math3.stat.descriptive; // // import java.util.ArrayList; // import java.util.Collection; // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.distribution.RealDistribution; // import org.apache.commons.math3.distribution.UniformRealDistribution; // import org.apache.commons.math3.distribution.IntegerDistribution; // import org.apache.commons.math3.distribution.UniformIntegerDistribution; // import org.apache.commons.math3.util.Precision; // import org.junit.Assert; // import org.junit.Test; // // // // public class AggregateSummaryStatisticsTest { // // // @Test // public void testAggregation(); // @Test // public void testAggregationConsistency(); // @Test // public void testAggregate(); // @Test // public void testAggregateDegenerate(); // @Test // public void testAggregateSpecialValues(); // protected static void assertEquals(StatisticalSummary expected, StatisticalSummary observed, double delta); // private double[] generateSample(); // private double[][] generatePartition(double[] sample); // } // You are a professional Java test case writer, please create a test case named `testAggregate` for the `AggregateSummaryStatistics` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test aggregate function by randomly generating a dataset of 10-100 values * from [-100, 100], dividing it into 2-5 partitions, computing stats for each * partition and comparing the result of aggregate(...) applied to the collection * of per-partition SummaryStatistics with a single SummaryStatistics computed * over the full sample. * */ @Test public void testAggregate() {
/** * Test aggregate function by randomly generating a dataset of 10-100 values * from [-100, 100], dividing it into 2-5 partitions, computing stats for each * partition and comparing the result of aggregate(...) applied to the collection * of per-partition SummaryStatistics with a single SummaryStatistics computed * over the full sample. * */
1
org.apache.commons.math3.stat.descriptive.AggregateSummaryStatistics
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.math3.stat.descriptive; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import org.apache.commons.math3.exception.NullArgumentException; public class AggregateSummaryStatistics implements StatisticalSummary, Serializable { private static final long serialVersionUID = -8207112444016386906L; private final SummaryStatistics statisticsPrototype; private final SummaryStatistics statistics; public AggregateSummaryStatistics(); public AggregateSummaryStatistics(SummaryStatistics prototypeStatistics) throws NullArgumentException; public AggregateSummaryStatistics(SummaryStatistics prototypeStatistics, SummaryStatistics initialStatistics); public double getMax(); public double getMean(); public double getMin(); public long getN(); public double getStandardDeviation(); public double getSum(); public double getVariance(); public double getSumOfLogs(); public double getGeometricMean(); public double getSumsq(); public double getSecondMoment(); public StatisticalSummary getSummary(); public SummaryStatistics createContributingStatistics(); public static StatisticalSummaryValues aggregate(Collection<SummaryStatistics> statistics); public AggregatingSummaryStatistics(SummaryStatistics aggregateStatistics); @Override public void addValue(double value); @Override public boolean equals(Object object); @Override public int hashCode(); } // Abstract Java Test Class package org.apache.commons.math3.stat.descriptive; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.distribution.RealDistribution; import org.apache.commons.math3.distribution.UniformRealDistribution; import org.apache.commons.math3.distribution.IntegerDistribution; import org.apache.commons.math3.distribution.UniformIntegerDistribution; import org.apache.commons.math3.util.Precision; import org.junit.Assert; import org.junit.Test; public class AggregateSummaryStatisticsTest { @Test public void testAggregation(); @Test public void testAggregationConsistency(); @Test public void testAggregate(); @Test public void testAggregateDegenerate(); @Test public void testAggregateSpecialValues(); protected static void assertEquals(StatisticalSummary expected, StatisticalSummary observed, double delta); private double[] generateSample(); private double[][] generatePartition(double[] sample); } ``` You are a professional Java test case writer, please create a test case named `testAggregate` for the `AggregateSummaryStatistics` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test aggregate function by randomly generating a dataset of 10-100 values * from [-100, 100], dividing it into 2-5 partitions, computing stats for each * partition and comparing the result of aggregate(...) applied to the collection * of per-partition SummaryStatistics with a single SummaryStatistics computed * over the full sample. * */ @Test public void testAggregate() { ```
public class AggregateSummaryStatistics implements StatisticalSummary, Serializable
package org.apache.commons.math3.stat.descriptive; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.distribution.RealDistribution; import org.apache.commons.math3.distribution.UniformRealDistribution; import org.apache.commons.math3.distribution.IntegerDistribution; import org.apache.commons.math3.distribution.UniformIntegerDistribution; import org.apache.commons.math3.util.Precision; import org.junit.Assert; import org.junit.Test;
@Test public void testAggregation(); @Test public void testAggregationConsistency(); @Test public void testAggregate(); @Test public void testAggregateDegenerate(); @Test public void testAggregateSpecialValues(); protected static void assertEquals(StatisticalSummary expected, StatisticalSummary observed, double delta); private double[] generateSample(); private double[][] generatePartition(double[] sample);
a964dd93449c91f54acb58efc8d014a9e6ae88384fe152d1ec76d573c61ea348
[ "org.apache.commons.math3.stat.descriptive.AggregateSummaryStatisticsTest::testAggregate" ]
private static final long serialVersionUID = -8207112444016386906L; private final SummaryStatistics statisticsPrototype; private final SummaryStatistics statistics;
@Test public void testAggregate()
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.descriptive; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.distribution.RealDistribution; import org.apache.commons.math3.distribution.UniformRealDistribution; import org.apache.commons.math3.distribution.IntegerDistribution; import org.apache.commons.math3.distribution.UniformIntegerDistribution; import org.apache.commons.math3.util.Precision; import org.junit.Assert; import org.junit.Test; /** * Test cases for {@link AggregateSummaryStatistics} * */ public class AggregateSummaryStatisticsTest { /** * Tests the standard aggregation behavior */ @Test public void testAggregation() { AggregateSummaryStatistics aggregate = new AggregateSummaryStatistics(); SummaryStatistics setOneStats = aggregate.createContributingStatistics(); SummaryStatistics setTwoStats = aggregate.createContributingStatistics(); Assert.assertNotNull("The set one contributing stats are null", setOneStats); Assert.assertNotNull("The set two contributing stats are null", setTwoStats); Assert.assertNotSame("Contributing stats objects are the same", setOneStats, setTwoStats); setOneStats.addValue(2); setOneStats.addValue(3); setOneStats.addValue(5); setOneStats.addValue(7); setOneStats.addValue(11); Assert.assertEquals("Wrong number of set one values", 5, setOneStats.getN()); Assert.assertTrue("Wrong sum of set one values", Precision.equals(28.0, setOneStats.getSum(), 1)); setTwoStats.addValue(2); setTwoStats.addValue(4); setTwoStats.addValue(8); Assert.assertEquals("Wrong number of set two values", 3, setTwoStats.getN()); Assert.assertTrue("Wrong sum of set two values", Precision.equals(14.0, setTwoStats.getSum(), 1)); Assert.assertEquals("Wrong number of aggregate values", 8, aggregate.getN()); Assert.assertTrue("Wrong aggregate sum", Precision.equals(42.0, aggregate.getSum(), 1)); } /** * Verify that aggregating over a partition gives the same results * as direct computation. * * 1) Randomly generate a dataset of 10-100 values * from [-100, 100] * 2) Divide the dataset it into 2-5 partitions * 3) Create an AggregateSummaryStatistic and ContributingStatistics * for each partition * 4) Compare results from the AggregateSummaryStatistic with values * returned by a single SummaryStatistics instance that is provided * the full dataset */ @Test public void testAggregationConsistency() { // Generate a random sample and random partition double[] totalSample = generateSample(); double[][] subSamples = generatePartition(totalSample); int nSamples = subSamples.length; // Create aggregator and total stats for comparison AggregateSummaryStatistics aggregate = new AggregateSummaryStatistics(); SummaryStatistics totalStats = new SummaryStatistics(); // Create array of component stats SummaryStatistics componentStats[] = new SummaryStatistics[nSamples]; for (int i = 0; i < nSamples; i++) { // Make componentStats[i] a contributing statistic to aggregate componentStats[i] = aggregate.createContributingStatistics(); // Add values from subsample for (int j = 0; j < subSamples[i].length; j++) { componentStats[i].addValue(subSamples[i][j]); } } // Compute totalStats directly for (int i = 0; i < totalSample.length; i++) { totalStats.addValue(totalSample[i]); } /* * Compare statistics in totalStats with aggregate. * Note that guaranteed success of this comparison depends on the * fact that <aggregate> gets values in exactly the same order * as <totalStats>. * */ Assert.assertEquals(totalStats.getSummary(), aggregate.getSummary()); } /** * Test aggregate function by randomly generating a dataset of 10-100 values * from [-100, 100], dividing it into 2-5 partitions, computing stats for each * partition and comparing the result of aggregate(...) applied to the collection * of per-partition SummaryStatistics with a single SummaryStatistics computed * over the full sample. * */ @Test public void testAggregate() { // Generate a random sample and random partition double[] totalSample = generateSample(); double[][] subSamples = generatePartition(totalSample); int nSamples = subSamples.length; // Compute combined stats directly SummaryStatistics totalStats = new SummaryStatistics(); for (int i = 0; i < totalSample.length; i++) { totalStats.addValue(totalSample[i]); } // Now compute subsample stats individually and aggregate SummaryStatistics[] subSampleStats = new SummaryStatistics[nSamples]; for (int i = 0; i < nSamples; i++) { subSampleStats[i] = new SummaryStatistics(); } Collection<SummaryStatistics> aggregate = new ArrayList<SummaryStatistics>(); for (int i = 0; i < nSamples; i++) { for (int j = 0; j < subSamples[i].length; j++) { subSampleStats[i].addValue(subSamples[i][j]); } aggregate.add(subSampleStats[i]); } // Compare values StatisticalSummary aggregatedStats = AggregateSummaryStatistics.aggregate(aggregate); assertEquals(totalStats.getSummary(), aggregatedStats, 10E-12); } @Test public void testAggregateDegenerate() { double[] totalSample = {1, 2, 3, 4, 5}; double[][] subSamples = {{1}, {2}, {3}, {4}, {5}}; // Compute combined stats directly SummaryStatistics totalStats = new SummaryStatistics(); for (int i = 0; i < totalSample.length; i++) { totalStats.addValue(totalSample[i]); } // Now compute subsample stats individually and aggregate SummaryStatistics[] subSampleStats = new SummaryStatistics[5]; for (int i = 0; i < 5; i++) { subSampleStats[i] = new SummaryStatistics(); } Collection<SummaryStatistics> aggregate = new ArrayList<SummaryStatistics>(); for (int i = 0; i < 5; i++) { for (int j = 0; j < subSamples[i].length; j++) { subSampleStats[i].addValue(subSamples[i][j]); } aggregate.add(subSampleStats[i]); } // Compare values StatisticalSummaryValues aggregatedStats = AggregateSummaryStatistics.aggregate(aggregate); assertEquals(totalStats.getSummary(), aggregatedStats, 10E-12); } @Test public void testAggregateSpecialValues() { double[] totalSample = {Double.POSITIVE_INFINITY, 2, 3, Double.NaN, 5}; double[][] subSamples = {{Double.POSITIVE_INFINITY, 2}, {3}, {Double.NaN}, {5}}; // Compute combined stats directly SummaryStatistics totalStats = new SummaryStatistics(); for (int i = 0; i < totalSample.length; i++) { totalStats.addValue(totalSample[i]); } // Now compute subsample stats individually and aggregate SummaryStatistics[] subSampleStats = new SummaryStatistics[5]; for (int i = 0; i < 4; i++) { subSampleStats[i] = new SummaryStatistics(); } Collection<SummaryStatistics> aggregate = new ArrayList<SummaryStatistics>(); for (int i = 0; i < 4; i++) { for (int j = 0; j < subSamples[i].length; j++) { subSampleStats[i].addValue(subSamples[i][j]); } aggregate.add(subSampleStats[i]); } // Compare values StatisticalSummaryValues aggregatedStats = AggregateSummaryStatistics.aggregate(aggregate); assertEquals(totalStats.getSummary(), aggregatedStats, 10E-12); } /** * Verifies that a StatisticalSummary and a StatisticalSummaryValues are equal up * to delta, with NaNs, infinities returned in the same spots. For max, min, n, values * have to agree exactly, delta is used only for sum, mean, variance, std dev. */ protected static void assertEquals(StatisticalSummary expected, StatisticalSummary observed, double delta) { TestUtils.assertEquals(expected.getMax(), observed.getMax(), 0); TestUtils.assertEquals(expected.getMin(), observed.getMin(), 0); Assert.assertEquals(expected.getN(), observed.getN()); TestUtils.assertEquals(expected.getSum(), observed.getSum(), delta); TestUtils.assertEquals(expected.getMean(), observed.getMean(), delta); TestUtils.assertEquals(expected.getStandardDeviation(), observed.getStandardDeviation(), delta); TestUtils.assertEquals(expected.getVariance(), observed.getVariance(), delta); } /** * Generates a random sample of double values. * Sample size is random, between 10 and 100 and values are * uniformly distributed over [-100, 100]. * * @return array of random double values */ private double[] generateSample() { final IntegerDistribution size = new UniformIntegerDistribution(10, 100); final RealDistribution randomData = new UniformRealDistribution(-100, 100); final int sampleSize = size.sample(); final double[] out = randomData.sample(sampleSize); return out; } /** * Generates a partition of <sample> into up to 5 sequentially selected * subsamples with randomly selected partition points. * * @param sample array to partition * @return rectangular array with rows = subsamples */ private double[][] generatePartition(double[] sample) { final int length = sample.length; final double[][] out = new double[5][]; int cur = 0; // beginning of current partition segment int offset = 0; // end of current partition segment int sampleCount = 0; // number of segments defined for (int i = 0; i < 5; i++) { if (cur == length || offset == length) { break; } final int next; if (i == 4 || cur == length - 1) { next = length - 1; } else { next = (new UniformIntegerDistribution(cur, length - 1)).sample(); } final int subLength = next - cur + 1; out[i] = new double[subLength]; System.arraycopy(sample, offset, out[i], 0, subLength); cur = next + 1; sampleCount++; offset += subLength; } if (sampleCount < 5) { double[][] out2 = new double[sampleCount][]; for (int j = 0; j < sampleCount; j++) { final int curSize = out[j].length; out2[j] = new double[curSize]; System.arraycopy(out[j], 0, out2[j], 0, curSize); } return out2; } else { return out; } } }
[ { "be_test_class_file": "org/apache/commons/math3/stat/descriptive/AggregateSummaryStatistics.java", "be_test_class_name": "org.apache.commons.math3.stat.descriptive.AggregateSummaryStatistics", "be_test_function_name": "aggregate", "be_test_function_signature": "(Ljava/util/Collection;)Lorg/apache/commons/math3/stat/descriptive/StatisticalSummaryValues;", "line_numbers": [ "307", "308", "310", "311", "312", "314", "315", "316", "317", "318", "319", "320", "321", "322", "323", "324", "326", "327", "329", "330", "331", "332", "333", "334", "335", "336", "338", "339", "340", "341", "343", "345" ], "method_line_rate": 0.875 } ]
public class SkippingIteratorTest<E> extends AbstractIteratorTest<E>
@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 */ } }
// // 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 `testRemoveFirst` for the `SkippingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test removing the first element. Verify that the element is removed from * the underlying collection. */
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();
213
testRemoveFirst
```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 `testRemoveFirst` for the `SkippingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test removing the first element. Verify that the element is removed from * the underlying collection. */
191
// // 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 `testRemoveFirst` for the `SkippingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Test removing the first element. Verify that the element is removed from * the underlying collection. */ @Test public void testRemoveFirst() {
/** * Test removing the first element. Verify that the element is removed from * the underlying collection. */
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 `testRemoveFirst` for the `SkippingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Test removing the first element. Verify that the element is removed from * the underlying collection. */ @Test public void testRemoveFirst() { ```
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();
abc55217222fd7b9fa0492b598461d82ab12eb4030ca32b1583fe1a1ec63f866
[ "org.apache.commons.collections4.iterators.SkippingIteratorTest::testRemoveFirst" ]
private final long offset; private long pos;
@Test public void testRemoveFirst()
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.75 } ]
public class AggregateSummaryStatisticsTest
@Test public void testAggregationConsistency() { // Generate a random sample and random partition double[] totalSample = generateSample(); double[][] subSamples = generatePartition(totalSample); int nSamples = subSamples.length; // Create aggregator and total stats for comparison AggregateSummaryStatistics aggregate = new AggregateSummaryStatistics(); SummaryStatistics totalStats = new SummaryStatistics(); // Create array of component stats SummaryStatistics componentStats[] = new SummaryStatistics[nSamples]; for (int i = 0; i < nSamples; i++) { // Make componentStats[i] a contributing statistic to aggregate componentStats[i] = aggregate.createContributingStatistics(); // Add values from subsample for (int j = 0; j < subSamples[i].length; j++) { componentStats[i].addValue(subSamples[i][j]); } } // Compute totalStats directly for (int i = 0; i < totalSample.length; i++) { totalStats.addValue(totalSample[i]); } /* * Compare statistics in totalStats with aggregate. * Note that guaranteed success of this comparison depends on the * fact that <aggregate> gets values in exactly the same order * as <totalStats>. * */ Assert.assertEquals(totalStats.getSummary(), aggregate.getSummary()); }
// // Abstract Java Tested Class // package org.apache.commons.math3.stat.descriptive; // // import java.io.Serializable; // import java.util.Collection; // import java.util.Iterator; // import org.apache.commons.math3.exception.NullArgumentException; // // // // public class AggregateSummaryStatistics implements StatisticalSummary, // Serializable { // private static final long serialVersionUID = -8207112444016386906L; // private final SummaryStatistics statisticsPrototype; // private final SummaryStatistics statistics; // // public AggregateSummaryStatistics(); // public AggregateSummaryStatistics(SummaryStatistics prototypeStatistics) throws NullArgumentException; // public AggregateSummaryStatistics(SummaryStatistics prototypeStatistics, // SummaryStatistics initialStatistics); // public double getMax(); // public double getMean(); // public double getMin(); // public long getN(); // public double getStandardDeviation(); // public double getSum(); // public double getVariance(); // public double getSumOfLogs(); // public double getGeometricMean(); // public double getSumsq(); // public double getSecondMoment(); // public StatisticalSummary getSummary(); // public SummaryStatistics createContributingStatistics(); // public static StatisticalSummaryValues aggregate(Collection<SummaryStatistics> statistics); // public AggregatingSummaryStatistics(SummaryStatistics aggregateStatistics); // @Override // public void addValue(double value); // @Override // public boolean equals(Object object); // @Override // public int hashCode(); // } // // // Abstract Java Test Class // package org.apache.commons.math3.stat.descriptive; // // import java.util.ArrayList; // import java.util.Collection; // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.distribution.RealDistribution; // import org.apache.commons.math3.distribution.UniformRealDistribution; // import org.apache.commons.math3.distribution.IntegerDistribution; // import org.apache.commons.math3.distribution.UniformIntegerDistribution; // import org.apache.commons.math3.util.Precision; // import org.junit.Assert; // import org.junit.Test; // // // // public class AggregateSummaryStatisticsTest { // // // @Test // public void testAggregation(); // @Test // public void testAggregationConsistency(); // @Test // public void testAggregate(); // @Test // public void testAggregateDegenerate(); // @Test // public void testAggregateSpecialValues(); // protected static void assertEquals(StatisticalSummary expected, StatisticalSummary observed, double delta); // private double[] generateSample(); // private double[][] generatePartition(double[] sample); // } // You are a professional Java test case writer, please create a test case named `testAggregationConsistency` for the `AggregateSummaryStatistics` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Verify that aggregating over a partition gives the same results * as direct computation. * * 1) Randomly generate a dataset of 10-100 values * from [-100, 100] * 2) Divide the dataset it into 2-5 partitions * 3) Create an AggregateSummaryStatistic and ContributingStatistics * for each partition * 4) Compare results from the AggregateSummaryStatistic with values * returned by a single SummaryStatistics instance that is provided * the full dataset */
src/test/java/org/apache/commons/math3/stat/descriptive/AggregateSummaryStatisticsTest.java
package org.apache.commons.math3.stat.descriptive; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import org.apache.commons.math3.exception.NullArgumentException;
public AggregateSummaryStatistics(); public AggregateSummaryStatistics(SummaryStatistics prototypeStatistics) throws NullArgumentException; public AggregateSummaryStatistics(SummaryStatistics prototypeStatistics, SummaryStatistics initialStatistics); public double getMax(); public double getMean(); public double getMin(); public long getN(); public double getStandardDeviation(); public double getSum(); public double getVariance(); public double getSumOfLogs(); public double getGeometricMean(); public double getSumsq(); public double getSecondMoment(); public StatisticalSummary getSummary(); public SummaryStatistics createContributingStatistics(); public static StatisticalSummaryValues aggregate(Collection<SummaryStatistics> statistics); public AggregatingSummaryStatistics(SummaryStatistics aggregateStatistics); @Override public void addValue(double value); @Override public boolean equals(Object object); @Override public int hashCode();
123
testAggregationConsistency
```java // Abstract Java Tested Class package org.apache.commons.math3.stat.descriptive; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import org.apache.commons.math3.exception.NullArgumentException; public class AggregateSummaryStatistics implements StatisticalSummary, Serializable { private static final long serialVersionUID = -8207112444016386906L; private final SummaryStatistics statisticsPrototype; private final SummaryStatistics statistics; public AggregateSummaryStatistics(); public AggregateSummaryStatistics(SummaryStatistics prototypeStatistics) throws NullArgumentException; public AggregateSummaryStatistics(SummaryStatistics prototypeStatistics, SummaryStatistics initialStatistics); public double getMax(); public double getMean(); public double getMin(); public long getN(); public double getStandardDeviation(); public double getSum(); public double getVariance(); public double getSumOfLogs(); public double getGeometricMean(); public double getSumsq(); public double getSecondMoment(); public StatisticalSummary getSummary(); public SummaryStatistics createContributingStatistics(); public static StatisticalSummaryValues aggregate(Collection<SummaryStatistics> statistics); public AggregatingSummaryStatistics(SummaryStatistics aggregateStatistics); @Override public void addValue(double value); @Override public boolean equals(Object object); @Override public int hashCode(); } // Abstract Java Test Class package org.apache.commons.math3.stat.descriptive; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.distribution.RealDistribution; import org.apache.commons.math3.distribution.UniformRealDistribution; import org.apache.commons.math3.distribution.IntegerDistribution; import org.apache.commons.math3.distribution.UniformIntegerDistribution; import org.apache.commons.math3.util.Precision; import org.junit.Assert; import org.junit.Test; public class AggregateSummaryStatisticsTest { @Test public void testAggregation(); @Test public void testAggregationConsistency(); @Test public void testAggregate(); @Test public void testAggregateDegenerate(); @Test public void testAggregateSpecialValues(); protected static void assertEquals(StatisticalSummary expected, StatisticalSummary observed, double delta); private double[] generateSample(); private double[][] generatePartition(double[] sample); } ``` You are a professional Java test case writer, please create a test case named `testAggregationConsistency` for the `AggregateSummaryStatistics` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Verify that aggregating over a partition gives the same results * as direct computation. * * 1) Randomly generate a dataset of 10-100 values * from [-100, 100] * 2) Divide the dataset it into 2-5 partitions * 3) Create an AggregateSummaryStatistic and ContributingStatistics * for each partition * 4) Compare results from the AggregateSummaryStatistic with values * returned by a single SummaryStatistics instance that is provided * the full dataset */
83
// // Abstract Java Tested Class // package org.apache.commons.math3.stat.descriptive; // // import java.io.Serializable; // import java.util.Collection; // import java.util.Iterator; // import org.apache.commons.math3.exception.NullArgumentException; // // // // public class AggregateSummaryStatistics implements StatisticalSummary, // Serializable { // private static final long serialVersionUID = -8207112444016386906L; // private final SummaryStatistics statisticsPrototype; // private final SummaryStatistics statistics; // // public AggregateSummaryStatistics(); // public AggregateSummaryStatistics(SummaryStatistics prototypeStatistics) throws NullArgumentException; // public AggregateSummaryStatistics(SummaryStatistics prototypeStatistics, // SummaryStatistics initialStatistics); // public double getMax(); // public double getMean(); // public double getMin(); // public long getN(); // public double getStandardDeviation(); // public double getSum(); // public double getVariance(); // public double getSumOfLogs(); // public double getGeometricMean(); // public double getSumsq(); // public double getSecondMoment(); // public StatisticalSummary getSummary(); // public SummaryStatistics createContributingStatistics(); // public static StatisticalSummaryValues aggregate(Collection<SummaryStatistics> statistics); // public AggregatingSummaryStatistics(SummaryStatistics aggregateStatistics); // @Override // public void addValue(double value); // @Override // public boolean equals(Object object); // @Override // public int hashCode(); // } // // // Abstract Java Test Class // package org.apache.commons.math3.stat.descriptive; // // import java.util.ArrayList; // import java.util.Collection; // import org.apache.commons.math3.TestUtils; // import org.apache.commons.math3.distribution.RealDistribution; // import org.apache.commons.math3.distribution.UniformRealDistribution; // import org.apache.commons.math3.distribution.IntegerDistribution; // import org.apache.commons.math3.distribution.UniformIntegerDistribution; // import org.apache.commons.math3.util.Precision; // import org.junit.Assert; // import org.junit.Test; // // // // public class AggregateSummaryStatisticsTest { // // // @Test // public void testAggregation(); // @Test // public void testAggregationConsistency(); // @Test // public void testAggregate(); // @Test // public void testAggregateDegenerate(); // @Test // public void testAggregateSpecialValues(); // protected static void assertEquals(StatisticalSummary expected, StatisticalSummary observed, double delta); // private double[] generateSample(); // private double[][] generatePartition(double[] sample); // } // You are a professional Java test case writer, please create a test case named `testAggregationConsistency` for the `AggregateSummaryStatistics` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Verify that aggregating over a partition gives the same results * as direct computation. * * 1) Randomly generate a dataset of 10-100 values * from [-100, 100] * 2) Divide the dataset it into 2-5 partitions * 3) Create an AggregateSummaryStatistic and ContributingStatistics * for each partition * 4) Compare results from the AggregateSummaryStatistic with values * returned by a single SummaryStatistics instance that is provided * the full dataset */ @Test public void testAggregationConsistency() {
/** * Verify that aggregating over a partition gives the same results * as direct computation. * * 1) Randomly generate a dataset of 10-100 values * from [-100, 100] * 2) Divide the dataset it into 2-5 partitions * 3) Create an AggregateSummaryStatistic and ContributingStatistics * for each partition * 4) Compare results from the AggregateSummaryStatistic with values * returned by a single SummaryStatistics instance that is provided * the full dataset */
1
org.apache.commons.math3.stat.descriptive.AggregateSummaryStatistics
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.math3.stat.descriptive; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import org.apache.commons.math3.exception.NullArgumentException; public class AggregateSummaryStatistics implements StatisticalSummary, Serializable { private static final long serialVersionUID = -8207112444016386906L; private final SummaryStatistics statisticsPrototype; private final SummaryStatistics statistics; public AggregateSummaryStatistics(); public AggregateSummaryStatistics(SummaryStatistics prototypeStatistics) throws NullArgumentException; public AggregateSummaryStatistics(SummaryStatistics prototypeStatistics, SummaryStatistics initialStatistics); public double getMax(); public double getMean(); public double getMin(); public long getN(); public double getStandardDeviation(); public double getSum(); public double getVariance(); public double getSumOfLogs(); public double getGeometricMean(); public double getSumsq(); public double getSecondMoment(); public StatisticalSummary getSummary(); public SummaryStatistics createContributingStatistics(); public static StatisticalSummaryValues aggregate(Collection<SummaryStatistics> statistics); public AggregatingSummaryStatistics(SummaryStatistics aggregateStatistics); @Override public void addValue(double value); @Override public boolean equals(Object object); @Override public int hashCode(); } // Abstract Java Test Class package org.apache.commons.math3.stat.descriptive; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.distribution.RealDistribution; import org.apache.commons.math3.distribution.UniformRealDistribution; import org.apache.commons.math3.distribution.IntegerDistribution; import org.apache.commons.math3.distribution.UniformIntegerDistribution; import org.apache.commons.math3.util.Precision; import org.junit.Assert; import org.junit.Test; public class AggregateSummaryStatisticsTest { @Test public void testAggregation(); @Test public void testAggregationConsistency(); @Test public void testAggregate(); @Test public void testAggregateDegenerate(); @Test public void testAggregateSpecialValues(); protected static void assertEquals(StatisticalSummary expected, StatisticalSummary observed, double delta); private double[] generateSample(); private double[][] generatePartition(double[] sample); } ``` You are a professional Java test case writer, please create a test case named `testAggregationConsistency` for the `AggregateSummaryStatistics` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Verify that aggregating over a partition gives the same results * as direct computation. * * 1) Randomly generate a dataset of 10-100 values * from [-100, 100] * 2) Divide the dataset it into 2-5 partitions * 3) Create an AggregateSummaryStatistic and ContributingStatistics * for each partition * 4) Compare results from the AggregateSummaryStatistic with values * returned by a single SummaryStatistics instance that is provided * the full dataset */ @Test public void testAggregationConsistency() { ```
public class AggregateSummaryStatistics implements StatisticalSummary, Serializable
package org.apache.commons.math3.stat.descriptive; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.distribution.RealDistribution; import org.apache.commons.math3.distribution.UniformRealDistribution; import org.apache.commons.math3.distribution.IntegerDistribution; import org.apache.commons.math3.distribution.UniformIntegerDistribution; import org.apache.commons.math3.util.Precision; import org.junit.Assert; import org.junit.Test;
@Test public void testAggregation(); @Test public void testAggregationConsistency(); @Test public void testAggregate(); @Test public void testAggregateDegenerate(); @Test public void testAggregateSpecialValues(); protected static void assertEquals(StatisticalSummary expected, StatisticalSummary observed, double delta); private double[] generateSample(); private double[][] generatePartition(double[] sample);
af89dce23b2b9dad00573a0e0da8d2afce63f853e0648d6e2255a10c4b68a9c7
[ "org.apache.commons.math3.stat.descriptive.AggregateSummaryStatisticsTest::testAggregationConsistency" ]
private static final long serialVersionUID = -8207112444016386906L; private final SummaryStatistics statisticsPrototype; private final SummaryStatistics statistics;
@Test public void testAggregationConsistency()
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.descriptive; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.distribution.RealDistribution; import org.apache.commons.math3.distribution.UniformRealDistribution; import org.apache.commons.math3.distribution.IntegerDistribution; import org.apache.commons.math3.distribution.UniformIntegerDistribution; import org.apache.commons.math3.util.Precision; import org.junit.Assert; import org.junit.Test; /** * Test cases for {@link AggregateSummaryStatistics} * */ public class AggregateSummaryStatisticsTest { /** * Tests the standard aggregation behavior */ @Test public void testAggregation() { AggregateSummaryStatistics aggregate = new AggregateSummaryStatistics(); SummaryStatistics setOneStats = aggregate.createContributingStatistics(); SummaryStatistics setTwoStats = aggregate.createContributingStatistics(); Assert.assertNotNull("The set one contributing stats are null", setOneStats); Assert.assertNotNull("The set two contributing stats are null", setTwoStats); Assert.assertNotSame("Contributing stats objects are the same", setOneStats, setTwoStats); setOneStats.addValue(2); setOneStats.addValue(3); setOneStats.addValue(5); setOneStats.addValue(7); setOneStats.addValue(11); Assert.assertEquals("Wrong number of set one values", 5, setOneStats.getN()); Assert.assertTrue("Wrong sum of set one values", Precision.equals(28.0, setOneStats.getSum(), 1)); setTwoStats.addValue(2); setTwoStats.addValue(4); setTwoStats.addValue(8); Assert.assertEquals("Wrong number of set two values", 3, setTwoStats.getN()); Assert.assertTrue("Wrong sum of set two values", Precision.equals(14.0, setTwoStats.getSum(), 1)); Assert.assertEquals("Wrong number of aggregate values", 8, aggregate.getN()); Assert.assertTrue("Wrong aggregate sum", Precision.equals(42.0, aggregate.getSum(), 1)); } /** * Verify that aggregating over a partition gives the same results * as direct computation. * * 1) Randomly generate a dataset of 10-100 values * from [-100, 100] * 2) Divide the dataset it into 2-5 partitions * 3) Create an AggregateSummaryStatistic and ContributingStatistics * for each partition * 4) Compare results from the AggregateSummaryStatistic with values * returned by a single SummaryStatistics instance that is provided * the full dataset */ @Test public void testAggregationConsistency() { // Generate a random sample and random partition double[] totalSample = generateSample(); double[][] subSamples = generatePartition(totalSample); int nSamples = subSamples.length; // Create aggregator and total stats for comparison AggregateSummaryStatistics aggregate = new AggregateSummaryStatistics(); SummaryStatistics totalStats = new SummaryStatistics(); // Create array of component stats SummaryStatistics componentStats[] = new SummaryStatistics[nSamples]; for (int i = 0; i < nSamples; i++) { // Make componentStats[i] a contributing statistic to aggregate componentStats[i] = aggregate.createContributingStatistics(); // Add values from subsample for (int j = 0; j < subSamples[i].length; j++) { componentStats[i].addValue(subSamples[i][j]); } } // Compute totalStats directly for (int i = 0; i < totalSample.length; i++) { totalStats.addValue(totalSample[i]); } /* * Compare statistics in totalStats with aggregate. * Note that guaranteed success of this comparison depends on the * fact that <aggregate> gets values in exactly the same order * as <totalStats>. * */ Assert.assertEquals(totalStats.getSummary(), aggregate.getSummary()); } /** * Test aggregate function by randomly generating a dataset of 10-100 values * from [-100, 100], dividing it into 2-5 partitions, computing stats for each * partition and comparing the result of aggregate(...) applied to the collection * of per-partition SummaryStatistics with a single SummaryStatistics computed * over the full sample. * */ @Test public void testAggregate() { // Generate a random sample and random partition double[] totalSample = generateSample(); double[][] subSamples = generatePartition(totalSample); int nSamples = subSamples.length; // Compute combined stats directly SummaryStatistics totalStats = new SummaryStatistics(); for (int i = 0; i < totalSample.length; i++) { totalStats.addValue(totalSample[i]); } // Now compute subsample stats individually and aggregate SummaryStatistics[] subSampleStats = new SummaryStatistics[nSamples]; for (int i = 0; i < nSamples; i++) { subSampleStats[i] = new SummaryStatistics(); } Collection<SummaryStatistics> aggregate = new ArrayList<SummaryStatistics>(); for (int i = 0; i < nSamples; i++) { for (int j = 0; j < subSamples[i].length; j++) { subSampleStats[i].addValue(subSamples[i][j]); } aggregate.add(subSampleStats[i]); } // Compare values StatisticalSummary aggregatedStats = AggregateSummaryStatistics.aggregate(aggregate); assertEquals(totalStats.getSummary(), aggregatedStats, 10E-12); } @Test public void testAggregateDegenerate() { double[] totalSample = {1, 2, 3, 4, 5}; double[][] subSamples = {{1}, {2}, {3}, {4}, {5}}; // Compute combined stats directly SummaryStatistics totalStats = new SummaryStatistics(); for (int i = 0; i < totalSample.length; i++) { totalStats.addValue(totalSample[i]); } // Now compute subsample stats individually and aggregate SummaryStatistics[] subSampleStats = new SummaryStatistics[5]; for (int i = 0; i < 5; i++) { subSampleStats[i] = new SummaryStatistics(); } Collection<SummaryStatistics> aggregate = new ArrayList<SummaryStatistics>(); for (int i = 0; i < 5; i++) { for (int j = 0; j < subSamples[i].length; j++) { subSampleStats[i].addValue(subSamples[i][j]); } aggregate.add(subSampleStats[i]); } // Compare values StatisticalSummaryValues aggregatedStats = AggregateSummaryStatistics.aggregate(aggregate); assertEquals(totalStats.getSummary(), aggregatedStats, 10E-12); } @Test public void testAggregateSpecialValues() { double[] totalSample = {Double.POSITIVE_INFINITY, 2, 3, Double.NaN, 5}; double[][] subSamples = {{Double.POSITIVE_INFINITY, 2}, {3}, {Double.NaN}, {5}}; // Compute combined stats directly SummaryStatistics totalStats = new SummaryStatistics(); for (int i = 0; i < totalSample.length; i++) { totalStats.addValue(totalSample[i]); } // Now compute subsample stats individually and aggregate SummaryStatistics[] subSampleStats = new SummaryStatistics[5]; for (int i = 0; i < 4; i++) { subSampleStats[i] = new SummaryStatistics(); } Collection<SummaryStatistics> aggregate = new ArrayList<SummaryStatistics>(); for (int i = 0; i < 4; i++) { for (int j = 0; j < subSamples[i].length; j++) { subSampleStats[i].addValue(subSamples[i][j]); } aggregate.add(subSampleStats[i]); } // Compare values StatisticalSummaryValues aggregatedStats = AggregateSummaryStatistics.aggregate(aggregate); assertEquals(totalStats.getSummary(), aggregatedStats, 10E-12); } /** * Verifies that a StatisticalSummary and a StatisticalSummaryValues are equal up * to delta, with NaNs, infinities returned in the same spots. For max, min, n, values * have to agree exactly, delta is used only for sum, mean, variance, std dev. */ protected static void assertEquals(StatisticalSummary expected, StatisticalSummary observed, double delta) { TestUtils.assertEquals(expected.getMax(), observed.getMax(), 0); TestUtils.assertEquals(expected.getMin(), observed.getMin(), 0); Assert.assertEquals(expected.getN(), observed.getN()); TestUtils.assertEquals(expected.getSum(), observed.getSum(), delta); TestUtils.assertEquals(expected.getMean(), observed.getMean(), delta); TestUtils.assertEquals(expected.getStandardDeviation(), observed.getStandardDeviation(), delta); TestUtils.assertEquals(expected.getVariance(), observed.getVariance(), delta); } /** * Generates a random sample of double values. * Sample size is random, between 10 and 100 and values are * uniformly distributed over [-100, 100]. * * @return array of random double values */ private double[] generateSample() { final IntegerDistribution size = new UniformIntegerDistribution(10, 100); final RealDistribution randomData = new UniformRealDistribution(-100, 100); final int sampleSize = size.sample(); final double[] out = randomData.sample(sampleSize); return out; } /** * Generates a partition of <sample> into up to 5 sequentially selected * subsamples with randomly selected partition points. * * @param sample array to partition * @return rectangular array with rows = subsamples */ private double[][] generatePartition(double[] sample) { final int length = sample.length; final double[][] out = new double[5][]; int cur = 0; // beginning of current partition segment int offset = 0; // end of current partition segment int sampleCount = 0; // number of segments defined for (int i = 0; i < 5; i++) { if (cur == length || offset == length) { break; } final int next; if (i == 4 || cur == length - 1) { next = length - 1; } else { next = (new UniformIntegerDistribution(cur, length - 1)).sample(); } final int subLength = next - cur + 1; out[i] = new double[subLength]; System.arraycopy(sample, offset, out[i], 0, subLength); cur = next + 1; sampleCount++; offset += subLength; } if (sampleCount < 5) { double[][] out2 = new double[sampleCount][]; for (int j = 0; j < sampleCount; j++) { final int curSize = out[j].length; out2[j] = new double[curSize]; System.arraycopy(out[j], 0, out2[j], 0, curSize); } return out2; } else { return out; } } }
[ { "be_test_class_file": "org/apache/commons/math3/stat/descriptive/AggregateSummaryStatistics.java", "be_test_class_name": "org.apache.commons.math3.stat.descriptive.AggregateSummaryStatistics", "be_test_function_name": "createContributingStatistics", "be_test_function_signature": "()Lorg/apache/commons/math3/stat/descriptive/SummaryStatistics;", "line_numbers": [ "285", "289", "291" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/stat/descriptive/AggregateSummaryStatistics.java", "be_test_class_name": "org.apache.commons.math3.stat.descriptive.AggregateSummaryStatistics", "be_test_function_name": "getMax", "be_test_function_signature": "()D", "line_numbers": [ "139", "140", "141" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "org/apache/commons/math3/stat/descriptive/AggregateSummaryStatistics.java", "be_test_class_name": "org.apache.commons.math3.stat.descriptive.AggregateSummaryStatistics", "be_test_function_name": "getMean", "be_test_function_signature": "()D", "line_numbers": [ "150", "151", "152" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "org/apache/commons/math3/stat/descriptive/AggregateSummaryStatistics.java", "be_test_class_name": "org.apache.commons.math3.stat.descriptive.AggregateSummaryStatistics", "be_test_function_name": "getMin", "be_test_function_signature": "()D", "line_numbers": [ "162", "163", "164" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "org/apache/commons/math3/stat/descriptive/AggregateSummaryStatistics.java", "be_test_class_name": "org.apache.commons.math3.stat.descriptive.AggregateSummaryStatistics", "be_test_function_name": "getN", "be_test_function_signature": "()J", "line_numbers": [ "173", "174", "175" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "org/apache/commons/math3/stat/descriptive/AggregateSummaryStatistics.java", "be_test_class_name": "org.apache.commons.math3.stat.descriptive.AggregateSummaryStatistics", "be_test_function_name": "getSum", "be_test_function_signature": "()D", "line_numbers": [ "196", "197", "198" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "org/apache/commons/math3/stat/descriptive/AggregateSummaryStatistics.java", "be_test_class_name": "org.apache.commons.math3.stat.descriptive.AggregateSummaryStatistics", "be_test_function_name": "getSummary", "be_test_function_signature": "()Lorg/apache/commons/math3/stat/descriptive/StatisticalSummary;", "line_numbers": [ "270", "271", "273" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "org/apache/commons/math3/stat/descriptive/AggregateSummaryStatistics.java", "be_test_class_name": "org.apache.commons.math3.stat.descriptive.AggregateSummaryStatistics", "be_test_function_name": "getVariance", "be_test_function_signature": "()D", "line_numbers": [ "208", "209", "210" ], "method_line_rate": 0.6666666666666666 } ]
@SuppressWarnings("resource") public final class JsonReaderTest extends TestCase
public void testUnterminatedStringFailure() throws IOException { JsonReader reader = new JsonReader(reader("[\"string")); reader.setLenient(true); reader.beginArray(); assertEquals(JsonToken.STRING, reader.peek()); try { reader.nextString(); fail(); } catch (MalformedJsonException expected) { } }
// public void testSkipObject() throws IOException; // public void testSkipObjectAfterPeek() throws Exception; // public void testSkipInteger() throws IOException; // public void testSkipDouble() throws IOException; // public void testHelloWorld() throws IOException; // public void testInvalidJsonInput() throws IOException; // public void testNulls(); // public void testEmptyString(); // public void testCharacterUnescaping() throws IOException; // public void testUnescapingInvalidCharacters() throws IOException; // public void testUnescapingTruncatedCharacters() throws IOException; // public void testUnescapingTruncatedSequence() throws IOException; // public void testIntegersWithFractionalPartSpecified() throws IOException; // public void testDoubles() throws IOException; // public void testStrictNonFiniteDoubles() throws IOException; // public void testStrictQuotedNonFiniteDoubles() throws IOException; // public void testLenientNonFiniteDoubles() throws IOException; // public void testLenientQuotedNonFiniteDoubles() throws IOException; // public void testStrictNonFiniteDoublesWithSkipValue() throws IOException; // public void testLongs() throws IOException; // public void disabled_testNumberWithOctalPrefix() throws IOException; // public void testBooleans() throws IOException; // public void testPeekingUnquotedStringsPrefixedWithBooleans() throws IOException; // public void testMalformedNumbers() throws IOException; // private void assertNotANumber(String s) throws IOException; // public void testPeekingUnquotedStringsPrefixedWithIntegers() throws IOException; // public void testPeekLongMinValue() throws IOException; // public void testPeekLongMaxValue() throws IOException; // public void testLongLargerThanMaxLongThatWrapsAround() throws IOException; // public void testLongLargerThanMinLongThatWrapsAround() throws IOException; // public void testNegativeZero() throws Exception; // public void disabled_testPeekLargerThanLongMaxValue() throws IOException; // public void disabled_testPeekLargerThanLongMinValue() throws IOException; // public void disabled_testHighPrecisionLong() throws IOException; // public void testPeekMuchLargerThanLongMinValue() throws IOException; // public void testQuotedNumberWithEscape() throws IOException; // public void testMixedCaseLiterals() throws IOException; // public void testMissingValue() throws IOException; // public void testPrematureEndOfInput() throws IOException; // public void testPrematurelyClosed() throws IOException; // public void testNextFailuresDoNotAdvance() throws IOException; // public void testIntegerMismatchFailuresDoNotAdvance() throws IOException; // public void testStringNullIsNotNull() throws IOException; // public void testNullLiteralIsNotAString() throws IOException; // public void testStrictNameValueSeparator() throws IOException; // public void testLenientNameValueSeparator() throws IOException; // public void testStrictNameValueSeparatorWithSkipValue() throws IOException; // public void testCommentsInStringValue() throws Exception; // public void testStrictComments() throws IOException; // public void testLenientComments() throws IOException; // public void testStrictCommentsWithSkipValue() throws IOException; // public void testStrictUnquotedNames() throws IOException; // public void testLenientUnquotedNames() throws IOException; // public void testStrictUnquotedNamesWithSkipValue() throws IOException; // public void testStrictSingleQuotedNames() throws IOException; // public void testLenientSingleQuotedNames() throws IOException; // public void testStrictSingleQuotedNamesWithSkipValue() throws IOException; // public void testStrictUnquotedStrings() throws IOException; // public void testStrictUnquotedStringsWithSkipValue() throws IOException; // public void testLenientUnquotedStrings() throws IOException; // public void testStrictSingleQuotedStrings() throws IOException; // public void testLenientSingleQuotedStrings() throws IOException; // public void testStrictSingleQuotedStringsWithSkipValue() throws IOException; // public void testStrictSemicolonDelimitedArray() throws IOException; // public void testLenientSemicolonDelimitedArray() throws IOException; // public void testStrictSemicolonDelimitedArrayWithSkipValue() throws IOException; // public void testStrictSemicolonDelimitedNameValuePair() throws IOException; // public void testLenientSemicolonDelimitedNameValuePair() throws IOException; // public void testStrictSemicolonDelimitedNameValuePairWithSkipValue() throws IOException; // public void testStrictUnnecessaryArraySeparators() throws IOException; // public void testLenientUnnecessaryArraySeparators() throws IOException; // public void testStrictUnnecessaryArraySeparatorsWithSkipValue() throws IOException; // public void testStrictMultipleTopLevelValues() throws IOException; // public void testLenientMultipleTopLevelValues() throws IOException; // public void testStrictMultipleTopLevelValuesWithSkipValue() throws IOException; // public void testTopLevelValueTypes() throws IOException; // public void testTopLevelValueTypeWithSkipValue() throws IOException; // public void testStrictNonExecutePrefix(); // public void testStrictNonExecutePrefixWithSkipValue(); // public void testLenientNonExecutePrefix() throws IOException; // public void testLenientNonExecutePrefixWithLeadingWhitespace() throws IOException; // public void testLenientPartialNonExecutePrefix(); // public void testBomIgnoredAsFirstCharacterOfDocument() throws IOException; // public void testBomForbiddenAsOtherCharacterInDocument() throws IOException; // public void testFailWithPosition() throws IOException; // public void testFailWithPositionGreaterThanBufferSize() throws IOException; // public void testFailWithPositionOverSlashSlashEndOfLineComment() throws IOException; // public void testFailWithPositionOverHashEndOfLineComment() throws IOException; // public void testFailWithPositionOverCStyleComment() throws IOException; // public void testFailWithPositionOverQuotedString() throws IOException; // public void testFailWithPositionOverUnquotedString() throws IOException; // public void testFailWithEscapedNewlineCharacter() throws IOException; // public void testFailWithPositionIsOffsetByBom() throws IOException; // private void testFailWithPosition(String message, String json) throws IOException; // public void testFailWithPositionDeepPath() throws IOException; // public void testStrictVeryLongNumber() throws IOException; // public void testLenientVeryLongNumber() throws IOException; // public void testVeryLongUnquotedLiteral() throws IOException; // public void testDeeplyNestedArrays() throws IOException; // public void testDeeplyNestedObjects() throws IOException; // public void testStringEndingInSlash() throws IOException; // public void testDocumentWithCommentEndingInSlash() throws IOException; // public void testStringWithLeadingSlash() throws IOException; // public void testUnterminatedObject() throws IOException; // public void testVeryLongQuotedString() throws IOException; // public void testVeryLongUnquotedString() throws IOException; // public void testVeryLongUnterminatedString() throws IOException; // public void testSkipVeryLongUnquotedString() throws IOException; // public void testSkipTopLevelUnquotedString() throws IOException; // public void testSkipVeryLongQuotedString() throws IOException; // public void testSkipTopLevelQuotedString() throws IOException; // public void testStringAsNumberWithTruncatedExponent() throws IOException; // public void testStringAsNumberWithDigitAndNonDigitExponent() throws IOException; // public void testStringAsNumberWithNonDigitExponent() throws IOException; // public void testEmptyStringName() throws IOException; // public void testStrictExtraCommasInMaps() throws IOException; // public void testLenientExtraCommasInMaps() throws IOException; // private String repeat(char c, int count); // public void testMalformedDocuments() throws IOException; // public void testUnterminatedStringFailure() throws IOException; // private void assertDocument(String document, Object... expectations) throws IOException; // private Reader reader(final String s); // } // You are a professional Java test case writer, please create a test case named `testUnterminatedStringFailure` for the `JsonReader` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * This test behave slightly differently in Gson 2.2 and earlier. It fails * during peek rather than during nextString(). */
gson/src/test/java/com/google/gson/stream/JsonReaderTest.java
package com.google.gson.stream; import com.google.gson.internal.JsonReaderInternalAccess; import com.google.gson.internal.bind.JsonTreeReader; import java.io.Closeable; import java.io.EOFException; import java.io.IOException; import java.io.Reader;
public JsonReader(Reader in); public final void setLenient(boolean lenient); public final boolean isLenient(); public void beginArray() throws IOException; public void endArray() throws IOException; public void beginObject() throws IOException; public void endObject() throws IOException; public boolean hasNext() throws IOException; public JsonToken peek() throws IOException; int doPeek() throws IOException; private int peekKeyword() throws IOException; private int peekNumber() throws IOException; private boolean isLiteral(char c) throws IOException; public String nextName() throws IOException; public String nextString() throws IOException; public boolean nextBoolean() throws IOException; public void nextNull() throws IOException; public double nextDouble() throws IOException; public long nextLong() throws IOException; private String nextQuotedValue(char quote) throws IOException; @SuppressWarnings("fallthrough") private String nextUnquotedValue() throws IOException; private void skipQuotedValue(char quote) throws IOException; private void skipUnquotedValue() throws IOException; public int nextInt() throws IOException; public void close() throws IOException; public void skipValue() throws IOException; private void push(int newTop); private boolean fillBuffer(int minimum) throws IOException; private int nextNonWhitespace(boolean throwOnEof) throws IOException; private void checkLenient() throws IOException; private void skipToEndOfLine() throws IOException; private boolean skipTo(String toFind) throws IOException; @Override public String toString(); String locationString(); public String getPath(); private char readEscapeCharacter() throws IOException; private IOException syntaxError(String message) throws IOException; private void consumeNonExecutePrefix() throws IOException; @Override public void promoteNameToValue(JsonReader reader) throws IOException;
1,729
testUnterminatedStringFailure
```java public void testSkipObject() throws IOException; public void testSkipObjectAfterPeek() throws Exception; public void testSkipInteger() throws IOException; public void testSkipDouble() throws IOException; public void testHelloWorld() throws IOException; public void testInvalidJsonInput() throws IOException; public void testNulls(); public void testEmptyString(); public void testCharacterUnescaping() throws IOException; public void testUnescapingInvalidCharacters() throws IOException; public void testUnescapingTruncatedCharacters() throws IOException; public void testUnescapingTruncatedSequence() throws IOException; public void testIntegersWithFractionalPartSpecified() throws IOException; public void testDoubles() throws IOException; public void testStrictNonFiniteDoubles() throws IOException; public void testStrictQuotedNonFiniteDoubles() throws IOException; public void testLenientNonFiniteDoubles() throws IOException; public void testLenientQuotedNonFiniteDoubles() throws IOException; public void testStrictNonFiniteDoublesWithSkipValue() throws IOException; public void testLongs() throws IOException; public void disabled_testNumberWithOctalPrefix() throws IOException; public void testBooleans() throws IOException; public void testPeekingUnquotedStringsPrefixedWithBooleans() throws IOException; public void testMalformedNumbers() throws IOException; private void assertNotANumber(String s) throws IOException; public void testPeekingUnquotedStringsPrefixedWithIntegers() throws IOException; public void testPeekLongMinValue() throws IOException; public void testPeekLongMaxValue() throws IOException; public void testLongLargerThanMaxLongThatWrapsAround() throws IOException; public void testLongLargerThanMinLongThatWrapsAround() throws IOException; public void testNegativeZero() throws Exception; public void disabled_testPeekLargerThanLongMaxValue() throws IOException; public void disabled_testPeekLargerThanLongMinValue() throws IOException; public void disabled_testHighPrecisionLong() throws IOException; public void testPeekMuchLargerThanLongMinValue() throws IOException; public void testQuotedNumberWithEscape() throws IOException; public void testMixedCaseLiterals() throws IOException; public void testMissingValue() throws IOException; public void testPrematureEndOfInput() throws IOException; public void testPrematurelyClosed() throws IOException; public void testNextFailuresDoNotAdvance() throws IOException; public void testIntegerMismatchFailuresDoNotAdvance() throws IOException; public void testStringNullIsNotNull() throws IOException; public void testNullLiteralIsNotAString() throws IOException; public void testStrictNameValueSeparator() throws IOException; public void testLenientNameValueSeparator() throws IOException; public void testStrictNameValueSeparatorWithSkipValue() throws IOException; public void testCommentsInStringValue() throws Exception; public void testStrictComments() throws IOException; public void testLenientComments() throws IOException; public void testStrictCommentsWithSkipValue() throws IOException; public void testStrictUnquotedNames() throws IOException; public void testLenientUnquotedNames() throws IOException; public void testStrictUnquotedNamesWithSkipValue() throws IOException; public void testStrictSingleQuotedNames() throws IOException; public void testLenientSingleQuotedNames() throws IOException; public void testStrictSingleQuotedNamesWithSkipValue() throws IOException; public void testStrictUnquotedStrings() throws IOException; public void testStrictUnquotedStringsWithSkipValue() throws IOException; public void testLenientUnquotedStrings() throws IOException; public void testStrictSingleQuotedStrings() throws IOException; public void testLenientSingleQuotedStrings() throws IOException; public void testStrictSingleQuotedStringsWithSkipValue() throws IOException; public void testStrictSemicolonDelimitedArray() throws IOException; public void testLenientSemicolonDelimitedArray() throws IOException; public void testStrictSemicolonDelimitedArrayWithSkipValue() throws IOException; public void testStrictSemicolonDelimitedNameValuePair() throws IOException; public void testLenientSemicolonDelimitedNameValuePair() throws IOException; public void testStrictSemicolonDelimitedNameValuePairWithSkipValue() throws IOException; public void testStrictUnnecessaryArraySeparators() throws IOException; public void testLenientUnnecessaryArraySeparators() throws IOException; public void testStrictUnnecessaryArraySeparatorsWithSkipValue() throws IOException; public void testStrictMultipleTopLevelValues() throws IOException; public void testLenientMultipleTopLevelValues() throws IOException; public void testStrictMultipleTopLevelValuesWithSkipValue() throws IOException; public void testTopLevelValueTypes() throws IOException; public void testTopLevelValueTypeWithSkipValue() throws IOException; public void testStrictNonExecutePrefix(); public void testStrictNonExecutePrefixWithSkipValue(); public void testLenientNonExecutePrefix() throws IOException; public void testLenientNonExecutePrefixWithLeadingWhitespace() throws IOException; public void testLenientPartialNonExecutePrefix(); public void testBomIgnoredAsFirstCharacterOfDocument() throws IOException; public void testBomForbiddenAsOtherCharacterInDocument() throws IOException; public void testFailWithPosition() throws IOException; public void testFailWithPositionGreaterThanBufferSize() throws IOException; public void testFailWithPositionOverSlashSlashEndOfLineComment() throws IOException; public void testFailWithPositionOverHashEndOfLineComment() throws IOException; public void testFailWithPositionOverCStyleComment() throws IOException; public void testFailWithPositionOverQuotedString() throws IOException; public void testFailWithPositionOverUnquotedString() throws IOException; public void testFailWithEscapedNewlineCharacter() throws IOException; public void testFailWithPositionIsOffsetByBom() throws IOException; private void testFailWithPosition(String message, String json) throws IOException; public void testFailWithPositionDeepPath() throws IOException; public void testStrictVeryLongNumber() throws IOException; public void testLenientVeryLongNumber() throws IOException; public void testVeryLongUnquotedLiteral() throws IOException; public void testDeeplyNestedArrays() throws IOException; public void testDeeplyNestedObjects() throws IOException; public void testStringEndingInSlash() throws IOException; public void testDocumentWithCommentEndingInSlash() throws IOException; public void testStringWithLeadingSlash() throws IOException; public void testUnterminatedObject() throws IOException; public void testVeryLongQuotedString() throws IOException; public void testVeryLongUnquotedString() throws IOException; public void testVeryLongUnterminatedString() throws IOException; public void testSkipVeryLongUnquotedString() throws IOException; public void testSkipTopLevelUnquotedString() throws IOException; public void testSkipVeryLongQuotedString() throws IOException; public void testSkipTopLevelQuotedString() throws IOException; public void testStringAsNumberWithTruncatedExponent() throws IOException; public void testStringAsNumberWithDigitAndNonDigitExponent() throws IOException; public void testStringAsNumberWithNonDigitExponent() throws IOException; public void testEmptyStringName() throws IOException; public void testStrictExtraCommasInMaps() throws IOException; public void testLenientExtraCommasInMaps() throws IOException; private String repeat(char c, int count); public void testMalformedDocuments() throws IOException; public void testUnterminatedStringFailure() throws IOException; private void assertDocument(String document, Object... expectations) throws IOException; private Reader reader(final String s); } ``` You are a professional Java test case writer, please create a test case named `testUnterminatedStringFailure` for the `JsonReader` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * This test behave slightly differently in Gson 2.2 and earlier. It fails * during peek rather than during nextString(). */
1,719
// public void testSkipObject() throws IOException; // public void testSkipObjectAfterPeek() throws Exception; // public void testSkipInteger() throws IOException; // public void testSkipDouble() throws IOException; // public void testHelloWorld() throws IOException; // public void testInvalidJsonInput() throws IOException; // public void testNulls(); // public void testEmptyString(); // public void testCharacterUnescaping() throws IOException; // public void testUnescapingInvalidCharacters() throws IOException; // public void testUnescapingTruncatedCharacters() throws IOException; // public void testUnescapingTruncatedSequence() throws IOException; // public void testIntegersWithFractionalPartSpecified() throws IOException; // public void testDoubles() throws IOException; // public void testStrictNonFiniteDoubles() throws IOException; // public void testStrictQuotedNonFiniteDoubles() throws IOException; // public void testLenientNonFiniteDoubles() throws IOException; // public void testLenientQuotedNonFiniteDoubles() throws IOException; // public void testStrictNonFiniteDoublesWithSkipValue() throws IOException; // public void testLongs() throws IOException; // public void disabled_testNumberWithOctalPrefix() throws IOException; // public void testBooleans() throws IOException; // public void testPeekingUnquotedStringsPrefixedWithBooleans() throws IOException; // public void testMalformedNumbers() throws IOException; // private void assertNotANumber(String s) throws IOException; // public void testPeekingUnquotedStringsPrefixedWithIntegers() throws IOException; // public void testPeekLongMinValue() throws IOException; // public void testPeekLongMaxValue() throws IOException; // public void testLongLargerThanMaxLongThatWrapsAround() throws IOException; // public void testLongLargerThanMinLongThatWrapsAround() throws IOException; // public void testNegativeZero() throws Exception; // public void disabled_testPeekLargerThanLongMaxValue() throws IOException; // public void disabled_testPeekLargerThanLongMinValue() throws IOException; // public void disabled_testHighPrecisionLong() throws IOException; // public void testPeekMuchLargerThanLongMinValue() throws IOException; // public void testQuotedNumberWithEscape() throws IOException; // public void testMixedCaseLiterals() throws IOException; // public void testMissingValue() throws IOException; // public void testPrematureEndOfInput() throws IOException; // public void testPrematurelyClosed() throws IOException; // public void testNextFailuresDoNotAdvance() throws IOException; // public void testIntegerMismatchFailuresDoNotAdvance() throws IOException; // public void testStringNullIsNotNull() throws IOException; // public void testNullLiteralIsNotAString() throws IOException; // public void testStrictNameValueSeparator() throws IOException; // public void testLenientNameValueSeparator() throws IOException; // public void testStrictNameValueSeparatorWithSkipValue() throws IOException; // public void testCommentsInStringValue() throws Exception; // public void testStrictComments() throws IOException; // public void testLenientComments() throws IOException; // public void testStrictCommentsWithSkipValue() throws IOException; // public void testStrictUnquotedNames() throws IOException; // public void testLenientUnquotedNames() throws IOException; // public void testStrictUnquotedNamesWithSkipValue() throws IOException; // public void testStrictSingleQuotedNames() throws IOException; // public void testLenientSingleQuotedNames() throws IOException; // public void testStrictSingleQuotedNamesWithSkipValue() throws IOException; // public void testStrictUnquotedStrings() throws IOException; // public void testStrictUnquotedStringsWithSkipValue() throws IOException; // public void testLenientUnquotedStrings() throws IOException; // public void testStrictSingleQuotedStrings() throws IOException; // public void testLenientSingleQuotedStrings() throws IOException; // public void testStrictSingleQuotedStringsWithSkipValue() throws IOException; // public void testStrictSemicolonDelimitedArray() throws IOException; // public void testLenientSemicolonDelimitedArray() throws IOException; // public void testStrictSemicolonDelimitedArrayWithSkipValue() throws IOException; // public void testStrictSemicolonDelimitedNameValuePair() throws IOException; // public void testLenientSemicolonDelimitedNameValuePair() throws IOException; // public void testStrictSemicolonDelimitedNameValuePairWithSkipValue() throws IOException; // public void testStrictUnnecessaryArraySeparators() throws IOException; // public void testLenientUnnecessaryArraySeparators() throws IOException; // public void testStrictUnnecessaryArraySeparatorsWithSkipValue() throws IOException; // public void testStrictMultipleTopLevelValues() throws IOException; // public void testLenientMultipleTopLevelValues() throws IOException; // public void testStrictMultipleTopLevelValuesWithSkipValue() throws IOException; // public void testTopLevelValueTypes() throws IOException; // public void testTopLevelValueTypeWithSkipValue() throws IOException; // public void testStrictNonExecutePrefix(); // public void testStrictNonExecutePrefixWithSkipValue(); // public void testLenientNonExecutePrefix() throws IOException; // public void testLenientNonExecutePrefixWithLeadingWhitespace() throws IOException; // public void testLenientPartialNonExecutePrefix(); // public void testBomIgnoredAsFirstCharacterOfDocument() throws IOException; // public void testBomForbiddenAsOtherCharacterInDocument() throws IOException; // public void testFailWithPosition() throws IOException; // public void testFailWithPositionGreaterThanBufferSize() throws IOException; // public void testFailWithPositionOverSlashSlashEndOfLineComment() throws IOException; // public void testFailWithPositionOverHashEndOfLineComment() throws IOException; // public void testFailWithPositionOverCStyleComment() throws IOException; // public void testFailWithPositionOverQuotedString() throws IOException; // public void testFailWithPositionOverUnquotedString() throws IOException; // public void testFailWithEscapedNewlineCharacter() throws IOException; // public void testFailWithPositionIsOffsetByBom() throws IOException; // private void testFailWithPosition(String message, String json) throws IOException; // public void testFailWithPositionDeepPath() throws IOException; // public void testStrictVeryLongNumber() throws IOException; // public void testLenientVeryLongNumber() throws IOException; // public void testVeryLongUnquotedLiteral() throws IOException; // public void testDeeplyNestedArrays() throws IOException; // public void testDeeplyNestedObjects() throws IOException; // public void testStringEndingInSlash() throws IOException; // public void testDocumentWithCommentEndingInSlash() throws IOException; // public void testStringWithLeadingSlash() throws IOException; // public void testUnterminatedObject() throws IOException; // public void testVeryLongQuotedString() throws IOException; // public void testVeryLongUnquotedString() throws IOException; // public void testVeryLongUnterminatedString() throws IOException; // public void testSkipVeryLongUnquotedString() throws IOException; // public void testSkipTopLevelUnquotedString() throws IOException; // public void testSkipVeryLongQuotedString() throws IOException; // public void testSkipTopLevelQuotedString() throws IOException; // public void testStringAsNumberWithTruncatedExponent() throws IOException; // public void testStringAsNumberWithDigitAndNonDigitExponent() throws IOException; // public void testStringAsNumberWithNonDigitExponent() throws IOException; // public void testEmptyStringName() throws IOException; // public void testStrictExtraCommasInMaps() throws IOException; // public void testLenientExtraCommasInMaps() throws IOException; // private String repeat(char c, int count); // public void testMalformedDocuments() throws IOException; // public void testUnterminatedStringFailure() throws IOException; // private void assertDocument(String document, Object... expectations) throws IOException; // private Reader reader(final String s); // } // You are a professional Java test case writer, please create a test case named `testUnterminatedStringFailure` for the `JsonReader` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * This test behave slightly differently in Gson 2.2 and earlier. It fails * during peek rather than during nextString(). */ public void testUnterminatedStringFailure() throws IOException {
/** * This test behave slightly differently in Gson 2.2 and earlier. It fails * during peek rather than during nextString(). */
18
com.google.gson.stream.JsonReader
gson/src/test/java
```java public void testSkipObject() throws IOException; public void testSkipObjectAfterPeek() throws Exception; public void testSkipInteger() throws IOException; public void testSkipDouble() throws IOException; public void testHelloWorld() throws IOException; public void testInvalidJsonInput() throws IOException; public void testNulls(); public void testEmptyString(); public void testCharacterUnescaping() throws IOException; public void testUnescapingInvalidCharacters() throws IOException; public void testUnescapingTruncatedCharacters() throws IOException; public void testUnescapingTruncatedSequence() throws IOException; public void testIntegersWithFractionalPartSpecified() throws IOException; public void testDoubles() throws IOException; public void testStrictNonFiniteDoubles() throws IOException; public void testStrictQuotedNonFiniteDoubles() throws IOException; public void testLenientNonFiniteDoubles() throws IOException; public void testLenientQuotedNonFiniteDoubles() throws IOException; public void testStrictNonFiniteDoublesWithSkipValue() throws IOException; public void testLongs() throws IOException; public void disabled_testNumberWithOctalPrefix() throws IOException; public void testBooleans() throws IOException; public void testPeekingUnquotedStringsPrefixedWithBooleans() throws IOException; public void testMalformedNumbers() throws IOException; private void assertNotANumber(String s) throws IOException; public void testPeekingUnquotedStringsPrefixedWithIntegers() throws IOException; public void testPeekLongMinValue() throws IOException; public void testPeekLongMaxValue() throws IOException; public void testLongLargerThanMaxLongThatWrapsAround() throws IOException; public void testLongLargerThanMinLongThatWrapsAround() throws IOException; public void testNegativeZero() throws Exception; public void disabled_testPeekLargerThanLongMaxValue() throws IOException; public void disabled_testPeekLargerThanLongMinValue() throws IOException; public void disabled_testHighPrecisionLong() throws IOException; public void testPeekMuchLargerThanLongMinValue() throws IOException; public void testQuotedNumberWithEscape() throws IOException; public void testMixedCaseLiterals() throws IOException; public void testMissingValue() throws IOException; public void testPrematureEndOfInput() throws IOException; public void testPrematurelyClosed() throws IOException; public void testNextFailuresDoNotAdvance() throws IOException; public void testIntegerMismatchFailuresDoNotAdvance() throws IOException; public void testStringNullIsNotNull() throws IOException; public void testNullLiteralIsNotAString() throws IOException; public void testStrictNameValueSeparator() throws IOException; public void testLenientNameValueSeparator() throws IOException; public void testStrictNameValueSeparatorWithSkipValue() throws IOException; public void testCommentsInStringValue() throws Exception; public void testStrictComments() throws IOException; public void testLenientComments() throws IOException; public void testStrictCommentsWithSkipValue() throws IOException; public void testStrictUnquotedNames() throws IOException; public void testLenientUnquotedNames() throws IOException; public void testStrictUnquotedNamesWithSkipValue() throws IOException; public void testStrictSingleQuotedNames() throws IOException; public void testLenientSingleQuotedNames() throws IOException; public void testStrictSingleQuotedNamesWithSkipValue() throws IOException; public void testStrictUnquotedStrings() throws IOException; public void testStrictUnquotedStringsWithSkipValue() throws IOException; public void testLenientUnquotedStrings() throws IOException; public void testStrictSingleQuotedStrings() throws IOException; public void testLenientSingleQuotedStrings() throws IOException; public void testStrictSingleQuotedStringsWithSkipValue() throws IOException; public void testStrictSemicolonDelimitedArray() throws IOException; public void testLenientSemicolonDelimitedArray() throws IOException; public void testStrictSemicolonDelimitedArrayWithSkipValue() throws IOException; public void testStrictSemicolonDelimitedNameValuePair() throws IOException; public void testLenientSemicolonDelimitedNameValuePair() throws IOException; public void testStrictSemicolonDelimitedNameValuePairWithSkipValue() throws IOException; public void testStrictUnnecessaryArraySeparators() throws IOException; public void testLenientUnnecessaryArraySeparators() throws IOException; public void testStrictUnnecessaryArraySeparatorsWithSkipValue() throws IOException; public void testStrictMultipleTopLevelValues() throws IOException; public void testLenientMultipleTopLevelValues() throws IOException; public void testStrictMultipleTopLevelValuesWithSkipValue() throws IOException; public void testTopLevelValueTypes() throws IOException; public void testTopLevelValueTypeWithSkipValue() throws IOException; public void testStrictNonExecutePrefix(); public void testStrictNonExecutePrefixWithSkipValue(); public void testLenientNonExecutePrefix() throws IOException; public void testLenientNonExecutePrefixWithLeadingWhitespace() throws IOException; public void testLenientPartialNonExecutePrefix(); public void testBomIgnoredAsFirstCharacterOfDocument() throws IOException; public void testBomForbiddenAsOtherCharacterInDocument() throws IOException; public void testFailWithPosition() throws IOException; public void testFailWithPositionGreaterThanBufferSize() throws IOException; public void testFailWithPositionOverSlashSlashEndOfLineComment() throws IOException; public void testFailWithPositionOverHashEndOfLineComment() throws IOException; public void testFailWithPositionOverCStyleComment() throws IOException; public void testFailWithPositionOverQuotedString() throws IOException; public void testFailWithPositionOverUnquotedString() throws IOException; public void testFailWithEscapedNewlineCharacter() throws IOException; public void testFailWithPositionIsOffsetByBom() throws IOException; private void testFailWithPosition(String message, String json) throws IOException; public void testFailWithPositionDeepPath() throws IOException; public void testStrictVeryLongNumber() throws IOException; public void testLenientVeryLongNumber() throws IOException; public void testVeryLongUnquotedLiteral() throws IOException; public void testDeeplyNestedArrays() throws IOException; public void testDeeplyNestedObjects() throws IOException; public void testStringEndingInSlash() throws IOException; public void testDocumentWithCommentEndingInSlash() throws IOException; public void testStringWithLeadingSlash() throws IOException; public void testUnterminatedObject() throws IOException; public void testVeryLongQuotedString() throws IOException; public void testVeryLongUnquotedString() throws IOException; public void testVeryLongUnterminatedString() throws IOException; public void testSkipVeryLongUnquotedString() throws IOException; public void testSkipTopLevelUnquotedString() throws IOException; public void testSkipVeryLongQuotedString() throws IOException; public void testSkipTopLevelQuotedString() throws IOException; public void testStringAsNumberWithTruncatedExponent() throws IOException; public void testStringAsNumberWithDigitAndNonDigitExponent() throws IOException; public void testStringAsNumberWithNonDigitExponent() throws IOException; public void testEmptyStringName() throws IOException; public void testStrictExtraCommasInMaps() throws IOException; public void testLenientExtraCommasInMaps() throws IOException; private String repeat(char c, int count); public void testMalformedDocuments() throws IOException; public void testUnterminatedStringFailure() throws IOException; private void assertDocument(String document, Object... expectations) throws IOException; private Reader reader(final String s); } ``` You are a professional Java test case writer, please create a test case named `testUnterminatedStringFailure` for the `JsonReader` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * This test behave slightly differently in Gson 2.2 and earlier. It fails * during peek rather than during nextString(). */ public void testUnterminatedStringFailure() throws IOException { ```
public class JsonReader implements Closeable
package com.google.gson.stream; import java.io.EOFException; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.Arrays; import junit.framework.TestCase; import static com.google.gson.stream.JsonToken.BEGIN_ARRAY; import static com.google.gson.stream.JsonToken.BEGIN_OBJECT; import static com.google.gson.stream.JsonToken.BOOLEAN; import static com.google.gson.stream.JsonToken.END_ARRAY; import static com.google.gson.stream.JsonToken.END_OBJECT; import static com.google.gson.stream.JsonToken.NAME; import static com.google.gson.stream.JsonToken.NULL; import static com.google.gson.stream.JsonToken.NUMBER; import static com.google.gson.stream.JsonToken.STRING;
public void testReadArray() throws IOException; public void testReadEmptyArray() throws IOException; public void testReadObject() throws IOException; public void testReadEmptyObject() throws IOException; public void testSkipArray() throws IOException; public void testSkipArrayAfterPeek() throws Exception; public void testSkipTopLevelObject() throws Exception; public void testSkipObject() throws IOException; public void testSkipObjectAfterPeek() throws Exception; public void testSkipInteger() throws IOException; public void testSkipDouble() throws IOException; public void testHelloWorld() throws IOException; public void testInvalidJsonInput() throws IOException; public void testNulls(); public void testEmptyString(); public void testCharacterUnescaping() throws IOException; public void testUnescapingInvalidCharacters() throws IOException; public void testUnescapingTruncatedCharacters() throws IOException; public void testUnescapingTruncatedSequence() throws IOException; public void testIntegersWithFractionalPartSpecified() throws IOException; public void testDoubles() throws IOException; public void testStrictNonFiniteDoubles() throws IOException; public void testStrictQuotedNonFiniteDoubles() throws IOException; public void testLenientNonFiniteDoubles() throws IOException; public void testLenientQuotedNonFiniteDoubles() throws IOException; public void testStrictNonFiniteDoublesWithSkipValue() throws IOException; public void testLongs() throws IOException; public void disabled_testNumberWithOctalPrefix() throws IOException; public void testBooleans() throws IOException; public void testPeekingUnquotedStringsPrefixedWithBooleans() throws IOException; public void testMalformedNumbers() throws IOException; private void assertNotANumber(String s) throws IOException; public void testPeekingUnquotedStringsPrefixedWithIntegers() throws IOException; public void testPeekLongMinValue() throws IOException; public void testPeekLongMaxValue() throws IOException; public void testLongLargerThanMaxLongThatWrapsAround() throws IOException; public void testLongLargerThanMinLongThatWrapsAround() throws IOException; public void testNegativeZero() throws Exception; public void disabled_testPeekLargerThanLongMaxValue() throws IOException; public void disabled_testPeekLargerThanLongMinValue() throws IOException; public void disabled_testHighPrecisionLong() throws IOException; public void testPeekMuchLargerThanLongMinValue() throws IOException; public void testQuotedNumberWithEscape() throws IOException; public void testMixedCaseLiterals() throws IOException; public void testMissingValue() throws IOException; public void testPrematureEndOfInput() throws IOException; public void testPrematurelyClosed() throws IOException; public void testNextFailuresDoNotAdvance() throws IOException; public void testIntegerMismatchFailuresDoNotAdvance() throws IOException; public void testStringNullIsNotNull() throws IOException; public void testNullLiteralIsNotAString() throws IOException; public void testStrictNameValueSeparator() throws IOException; public void testLenientNameValueSeparator() throws IOException; public void testStrictNameValueSeparatorWithSkipValue() throws IOException; public void testCommentsInStringValue() throws Exception; public void testStrictComments() throws IOException; public void testLenientComments() throws IOException; public void testStrictCommentsWithSkipValue() throws IOException; public void testStrictUnquotedNames() throws IOException; public void testLenientUnquotedNames() throws IOException; public void testStrictUnquotedNamesWithSkipValue() throws IOException; public void testStrictSingleQuotedNames() throws IOException; public void testLenientSingleQuotedNames() throws IOException; public void testStrictSingleQuotedNamesWithSkipValue() throws IOException; public void testStrictUnquotedStrings() throws IOException; public void testStrictUnquotedStringsWithSkipValue() throws IOException; public void testLenientUnquotedStrings() throws IOException; public void testStrictSingleQuotedStrings() throws IOException; public void testLenientSingleQuotedStrings() throws IOException; public void testStrictSingleQuotedStringsWithSkipValue() throws IOException; public void testStrictSemicolonDelimitedArray() throws IOException; public void testLenientSemicolonDelimitedArray() throws IOException; public void testStrictSemicolonDelimitedArrayWithSkipValue() throws IOException; public void testStrictSemicolonDelimitedNameValuePair() throws IOException; public void testLenientSemicolonDelimitedNameValuePair() throws IOException; public void testStrictSemicolonDelimitedNameValuePairWithSkipValue() throws IOException; public void testStrictUnnecessaryArraySeparators() throws IOException; public void testLenientUnnecessaryArraySeparators() throws IOException; public void testStrictUnnecessaryArraySeparatorsWithSkipValue() throws IOException; public void testStrictMultipleTopLevelValues() throws IOException; public void testLenientMultipleTopLevelValues() throws IOException; public void testStrictMultipleTopLevelValuesWithSkipValue() throws IOException; public void testTopLevelValueTypes() throws IOException; public void testTopLevelValueTypeWithSkipValue() throws IOException; public void testStrictNonExecutePrefix(); public void testStrictNonExecutePrefixWithSkipValue(); public void testLenientNonExecutePrefix() throws IOException; public void testLenientNonExecutePrefixWithLeadingWhitespace() throws IOException; public void testLenientPartialNonExecutePrefix(); public void testBomIgnoredAsFirstCharacterOfDocument() throws IOException; public void testBomForbiddenAsOtherCharacterInDocument() throws IOException; public void testFailWithPosition() throws IOException; public void testFailWithPositionGreaterThanBufferSize() throws IOException; public void testFailWithPositionOverSlashSlashEndOfLineComment() throws IOException; public void testFailWithPositionOverHashEndOfLineComment() throws IOException; public void testFailWithPositionOverCStyleComment() throws IOException; public void testFailWithPositionOverQuotedString() throws IOException; public void testFailWithPositionOverUnquotedString() throws IOException; public void testFailWithEscapedNewlineCharacter() throws IOException; public void testFailWithPositionIsOffsetByBom() throws IOException; private void testFailWithPosition(String message, String json) throws IOException; public void testFailWithPositionDeepPath() throws IOException; public void testStrictVeryLongNumber() throws IOException; public void testLenientVeryLongNumber() throws IOException; public void testVeryLongUnquotedLiteral() throws IOException; public void testDeeplyNestedArrays() throws IOException; public void testDeeplyNestedObjects() throws IOException; public void testStringEndingInSlash() throws IOException; public void testDocumentWithCommentEndingInSlash() throws IOException; public void testStringWithLeadingSlash() throws IOException; public void testUnterminatedObject() throws IOException; public void testVeryLongQuotedString() throws IOException; public void testVeryLongUnquotedString() throws IOException; public void testVeryLongUnterminatedString() throws IOException; public void testSkipVeryLongUnquotedString() throws IOException; public void testSkipTopLevelUnquotedString() throws IOException; public void testSkipVeryLongQuotedString() throws IOException; public void testSkipTopLevelQuotedString() throws IOException; public void testStringAsNumberWithTruncatedExponent() throws IOException; public void testStringAsNumberWithDigitAndNonDigitExponent() throws IOException; public void testStringAsNumberWithNonDigitExponent() throws IOException; public void testEmptyStringName() throws IOException; public void testStrictExtraCommasInMaps() throws IOException; public void testLenientExtraCommasInMaps() throws IOException; private String repeat(char c, int count); public void testMalformedDocuments() throws IOException; public void testUnterminatedStringFailure() throws IOException; private void assertDocument(String document, Object... expectations) throws IOException; private Reader reader(final String s);
aff77bc307f21a1b2261239b47c98f2ceab8a38c7228637fe4df049c1b8aaf0e
[ "com.google.gson.stream.JsonReaderTest::testUnterminatedStringFailure" ]
private static final char[] NON_EXECUTE_PREFIX = ")]}'\n".toCharArray(); private static final long MIN_INCOMPLETE_INTEGER = Long.MIN_VALUE / 10; private static final int PEEKED_NONE = 0; private static final int PEEKED_BEGIN_OBJECT = 1; private static final int PEEKED_END_OBJECT = 2; private static final int PEEKED_BEGIN_ARRAY = 3; private static final int PEEKED_END_ARRAY = 4; private static final int PEEKED_TRUE = 5; private static final int PEEKED_FALSE = 6; private static final int PEEKED_NULL = 7; private static final int PEEKED_SINGLE_QUOTED = 8; private static final int PEEKED_DOUBLE_QUOTED = 9; private static final int PEEKED_UNQUOTED = 10; private static final int PEEKED_BUFFERED = 11; private static final int PEEKED_SINGLE_QUOTED_NAME = 12; private static final int PEEKED_DOUBLE_QUOTED_NAME = 13; private static final int PEEKED_UNQUOTED_NAME = 14; private static final int PEEKED_LONG = 15; private static final int PEEKED_NUMBER = 16; private static final int PEEKED_EOF = 17; private static final int NUMBER_CHAR_NONE = 0; private static final int NUMBER_CHAR_SIGN = 1; private static final int NUMBER_CHAR_DIGIT = 2; private static final int NUMBER_CHAR_DECIMAL = 3; private static final int NUMBER_CHAR_FRACTION_DIGIT = 4; private static final int NUMBER_CHAR_EXP_E = 5; private static final int NUMBER_CHAR_EXP_SIGN = 6; private static final int NUMBER_CHAR_EXP_DIGIT = 7; private final Reader in; private boolean lenient = false; private final char[] buffer = new char[1024]; private int pos = 0; private int limit = 0; private int lineNumber = 0; private int lineStart = 0; int peeked = PEEKED_NONE; private long peekedLong; private int peekedNumberLength; private String peekedString; private int[] stack = new int[32]; private int stackSize = 0; private String[] pathNames = new String[32]; private int[] pathIndices = new int[32];
public void testUnterminatedStringFailure() throws IOException
Gson
/* * Copyright (C) 2010 Google Inc. * * 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.gson.stream; import java.io.EOFException; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.Arrays; import junit.framework.TestCase; import static com.google.gson.stream.JsonToken.BEGIN_ARRAY; import static com.google.gson.stream.JsonToken.BEGIN_OBJECT; import static com.google.gson.stream.JsonToken.BOOLEAN; import static com.google.gson.stream.JsonToken.END_ARRAY; import static com.google.gson.stream.JsonToken.END_OBJECT; import static com.google.gson.stream.JsonToken.NAME; import static com.google.gson.stream.JsonToken.NULL; import static com.google.gson.stream.JsonToken.NUMBER; import static com.google.gson.stream.JsonToken.STRING; @SuppressWarnings("resource") public final class JsonReaderTest extends TestCase { public void testReadArray() throws IOException { JsonReader reader = new JsonReader(reader("[true, true]")); reader.beginArray(); assertEquals(true, reader.nextBoolean()); assertEquals(true, reader.nextBoolean()); reader.endArray(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testReadEmptyArray() throws IOException { JsonReader reader = new JsonReader(reader("[]")); reader.beginArray(); assertFalse(reader.hasNext()); reader.endArray(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testReadObject() throws IOException { JsonReader reader = new JsonReader(reader( "{\"a\": \"android\", \"b\": \"banana\"}")); reader.beginObject(); assertEquals("a", reader.nextName()); assertEquals("android", reader.nextString()); assertEquals("b", reader.nextName()); assertEquals("banana", reader.nextString()); reader.endObject(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testReadEmptyObject() throws IOException { JsonReader reader = new JsonReader(reader("{}")); reader.beginObject(); assertFalse(reader.hasNext()); reader.endObject(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testSkipArray() throws IOException { JsonReader reader = new JsonReader(reader( "{\"a\": [\"one\", \"two\", \"three\"], \"b\": 123}")); reader.beginObject(); assertEquals("a", reader.nextName()); reader.skipValue(); assertEquals("b", reader.nextName()); assertEquals(123, reader.nextInt()); reader.endObject(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testSkipArrayAfterPeek() throws Exception { JsonReader reader = new JsonReader(reader( "{\"a\": [\"one\", \"two\", \"three\"], \"b\": 123}")); reader.beginObject(); assertEquals("a", reader.nextName()); assertEquals(BEGIN_ARRAY, reader.peek()); reader.skipValue(); assertEquals("b", reader.nextName()); assertEquals(123, reader.nextInt()); reader.endObject(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testSkipTopLevelObject() throws Exception { JsonReader reader = new JsonReader(reader( "{\"a\": [\"one\", \"two\", \"three\"], \"b\": 123}")); reader.skipValue(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testSkipObject() throws IOException { JsonReader reader = new JsonReader(reader( "{\"a\": { \"c\": [], \"d\": [true, true, {}] }, \"b\": \"banana\"}")); reader.beginObject(); assertEquals("a", reader.nextName()); reader.skipValue(); assertEquals("b", reader.nextName()); reader.skipValue(); reader.endObject(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testSkipObjectAfterPeek() throws Exception { String json = "{" + " \"one\": { \"num\": 1 }" + ", \"two\": { \"num\": 2 }" + ", \"three\": { \"num\": 3 }" + "}"; JsonReader reader = new JsonReader(reader(json)); reader.beginObject(); assertEquals("one", reader.nextName()); assertEquals(BEGIN_OBJECT, reader.peek()); reader.skipValue(); assertEquals("two", reader.nextName()); assertEquals(BEGIN_OBJECT, reader.peek()); reader.skipValue(); assertEquals("three", reader.nextName()); reader.skipValue(); reader.endObject(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testSkipInteger() throws IOException { JsonReader reader = new JsonReader(reader( "{\"a\":123456789,\"b\":-123456789}")); reader.beginObject(); assertEquals("a", reader.nextName()); reader.skipValue(); assertEquals("b", reader.nextName()); reader.skipValue(); reader.endObject(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testSkipDouble() throws IOException { JsonReader reader = new JsonReader(reader( "{\"a\":-123.456e-789,\"b\":123456789.0}")); reader.beginObject(); assertEquals("a", reader.nextName()); reader.skipValue(); assertEquals("b", reader.nextName()); reader.skipValue(); reader.endObject(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testHelloWorld() throws IOException { String json = "{\n" + " \"hello\": true,\n" + " \"foo\": [\"world\"]\n" + "}"; JsonReader reader = new JsonReader(reader(json)); reader.beginObject(); assertEquals("hello", reader.nextName()); assertEquals(true, reader.nextBoolean()); assertEquals("foo", reader.nextName()); reader.beginArray(); assertEquals("world", reader.nextString()); reader.endArray(); reader.endObject(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testInvalidJsonInput() throws IOException { String json = "{\n" + " \"h\\ello\": true,\n" + " \"foo\": [\"world\"]\n" + "}"; JsonReader reader = new JsonReader(reader(json)); reader.beginObject(); try { reader.nextName(); fail(); } catch (IOException expected) { } } public void testNulls() { try { new JsonReader(null); fail(); } catch (NullPointerException expected) { } } public void testEmptyString() { try { new JsonReader(reader("")).beginArray(); fail(); } catch (IOException expected) { } try { new JsonReader(reader("")).beginObject(); fail(); } catch (IOException expected) { } } public void testCharacterUnescaping() throws IOException { String json = "[\"a\"," + "\"a\\\"\"," + "\"\\\"\"," + "\":\"," + "\",\"," + "\"\\b\"," + "\"\\f\"," + "\"\\n\"," + "\"\\r\"," + "\"\\t\"," + "\" \"," + "\"\\\\\"," + "\"{\"," + "\"}\"," + "\"[\"," + "\"]\"," + "\"\\u0000\"," + "\"\\u0019\"," + "\"\\u20AC\"" + "]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); assertEquals("a", reader.nextString()); assertEquals("a\"", reader.nextString()); assertEquals("\"", reader.nextString()); assertEquals(":", reader.nextString()); assertEquals(",", reader.nextString()); assertEquals("\b", reader.nextString()); assertEquals("\f", reader.nextString()); assertEquals("\n", reader.nextString()); assertEquals("\r", reader.nextString()); assertEquals("\t", reader.nextString()); assertEquals(" ", reader.nextString()); assertEquals("\\", reader.nextString()); assertEquals("{", reader.nextString()); assertEquals("}", reader.nextString()); assertEquals("[", reader.nextString()); assertEquals("]", reader.nextString()); assertEquals("\0", reader.nextString()); assertEquals("\u0019", reader.nextString()); assertEquals("\u20AC", reader.nextString()); reader.endArray(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testUnescapingInvalidCharacters() throws IOException { String json = "[\"\\u000g\"]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); try { reader.nextString(); fail(); } catch (NumberFormatException expected) { } } public void testUnescapingTruncatedCharacters() throws IOException { String json = "[\"\\u000"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); try { reader.nextString(); fail(); } catch (IOException expected) { } } public void testUnescapingTruncatedSequence() throws IOException { String json = "[\"\\"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); try { reader.nextString(); fail(); } catch (IOException expected) { } } public void testIntegersWithFractionalPartSpecified() throws IOException { JsonReader reader = new JsonReader(reader("[1.0,1.0,1.0]")); reader.beginArray(); assertEquals(1.0, reader.nextDouble()); assertEquals(1, reader.nextInt()); assertEquals(1L, reader.nextLong()); } public void testDoubles() throws IOException { String json = "[-0.0," + "1.0," + "1.7976931348623157E308," + "4.9E-324," + "0.0," + "-0.5," + "2.2250738585072014E-308," + "3.141592653589793," + "2.718281828459045]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); assertEquals(-0.0, reader.nextDouble()); assertEquals(1.0, reader.nextDouble()); assertEquals(1.7976931348623157E308, reader.nextDouble()); assertEquals(4.9E-324, reader.nextDouble()); assertEquals(0.0, reader.nextDouble()); assertEquals(-0.5, reader.nextDouble()); assertEquals(2.2250738585072014E-308, reader.nextDouble()); assertEquals(3.141592653589793, reader.nextDouble()); assertEquals(2.718281828459045, reader.nextDouble()); reader.endArray(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testStrictNonFiniteDoubles() throws IOException { String json = "[NaN]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); try { reader.nextDouble(); fail(); } catch (MalformedJsonException expected) { } } public void testStrictQuotedNonFiniteDoubles() throws IOException { String json = "[\"NaN\"]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); try { reader.nextDouble(); fail(); } catch (MalformedJsonException expected) { } } public void testLenientNonFiniteDoubles() throws IOException { String json = "[NaN, -Infinity, Infinity]"; JsonReader reader = new JsonReader(reader(json)); reader.setLenient(true); reader.beginArray(); assertTrue(Double.isNaN(reader.nextDouble())); assertEquals(Double.NEGATIVE_INFINITY, reader.nextDouble()); assertEquals(Double.POSITIVE_INFINITY, reader.nextDouble()); reader.endArray(); } public void testLenientQuotedNonFiniteDoubles() throws IOException { String json = "[\"NaN\", \"-Infinity\", \"Infinity\"]"; JsonReader reader = new JsonReader(reader(json)); reader.setLenient(true); reader.beginArray(); assertTrue(Double.isNaN(reader.nextDouble())); assertEquals(Double.NEGATIVE_INFINITY, reader.nextDouble()); assertEquals(Double.POSITIVE_INFINITY, reader.nextDouble()); reader.endArray(); } public void testStrictNonFiniteDoublesWithSkipValue() throws IOException { String json = "[NaN]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); try { reader.skipValue(); fail(); } catch (MalformedJsonException expected) { } } public void testLongs() throws IOException { String json = "[0,0,0," + "1,1,1," + "-1,-1,-1," + "-9223372036854775808," + "9223372036854775807]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); assertEquals(0L, reader.nextLong()); assertEquals(0, reader.nextInt()); assertEquals(0.0, reader.nextDouble()); assertEquals(1L, reader.nextLong()); assertEquals(1, reader.nextInt()); assertEquals(1.0, reader.nextDouble()); assertEquals(-1L, reader.nextLong()); assertEquals(-1, reader.nextInt()); assertEquals(-1.0, reader.nextDouble()); try { reader.nextInt(); fail(); } catch (NumberFormatException expected) { } assertEquals(Long.MIN_VALUE, reader.nextLong()); try { reader.nextInt(); fail(); } catch (NumberFormatException expected) { } assertEquals(Long.MAX_VALUE, reader.nextLong()); reader.endArray(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void disabled_testNumberWithOctalPrefix() throws IOException { String json = "[01]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); try { reader.peek(); fail(); } catch (MalformedJsonException expected) { } try { reader.nextInt(); fail(); } catch (MalformedJsonException expected) { } try { reader.nextLong(); fail(); } catch (MalformedJsonException expected) { } try { reader.nextDouble(); fail(); } catch (MalformedJsonException expected) { } assertEquals("01", reader.nextString()); reader.endArray(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testBooleans() throws IOException { JsonReader reader = new JsonReader(reader("[true,false]")); reader.beginArray(); assertEquals(true, reader.nextBoolean()); assertEquals(false, reader.nextBoolean()); reader.endArray(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testPeekingUnquotedStringsPrefixedWithBooleans() throws IOException { JsonReader reader = new JsonReader(reader("[truey]")); reader.setLenient(true); reader.beginArray(); assertEquals(STRING, reader.peek()); try { reader.nextBoolean(); fail(); } catch (IllegalStateException expected) { } assertEquals("truey", reader.nextString()); reader.endArray(); } public void testMalformedNumbers() throws IOException { assertNotANumber("-"); assertNotANumber("."); // exponent lacks digit assertNotANumber("e"); assertNotANumber("0e"); assertNotANumber(".e"); assertNotANumber("0.e"); assertNotANumber("-.0e"); // no integer assertNotANumber("e1"); assertNotANumber(".e1"); assertNotANumber("-e1"); // trailing characters assertNotANumber("1x"); assertNotANumber("1.1x"); assertNotANumber("1e1x"); assertNotANumber("1ex"); assertNotANumber("1.1ex"); assertNotANumber("1.1e1x"); // fraction has no digit assertNotANumber("0."); assertNotANumber("-0."); assertNotANumber("0.e1"); assertNotANumber("-0.e1"); // no leading digit assertNotANumber(".0"); assertNotANumber("-.0"); assertNotANumber(".0e1"); assertNotANumber("-.0e1"); } private void assertNotANumber(String s) throws IOException { JsonReader reader = new JsonReader(reader("[" + s + "]")); reader.setLenient(true); reader.beginArray(); assertEquals(JsonToken.STRING, reader.peek()); assertEquals(s, reader.nextString()); reader.endArray(); } public void testPeekingUnquotedStringsPrefixedWithIntegers() throws IOException { JsonReader reader = new JsonReader(reader("[12.34e5x]")); reader.setLenient(true); reader.beginArray(); assertEquals(STRING, reader.peek()); try { reader.nextInt(); fail(); } catch (NumberFormatException expected) { } assertEquals("12.34e5x", reader.nextString()); } public void testPeekLongMinValue() throws IOException { JsonReader reader = new JsonReader(reader("[-9223372036854775808]")); reader.setLenient(true); reader.beginArray(); assertEquals(NUMBER, reader.peek()); assertEquals(-9223372036854775808L, reader.nextLong()); } public void testPeekLongMaxValue() throws IOException { JsonReader reader = new JsonReader(reader("[9223372036854775807]")); reader.setLenient(true); reader.beginArray(); assertEquals(NUMBER, reader.peek()); assertEquals(9223372036854775807L, reader.nextLong()); } public void testLongLargerThanMaxLongThatWrapsAround() throws IOException { JsonReader reader = new JsonReader(reader("[22233720368547758070]")); reader.setLenient(true); reader.beginArray(); assertEquals(NUMBER, reader.peek()); try { reader.nextLong(); fail(); } catch (NumberFormatException expected) { } } public void testLongLargerThanMinLongThatWrapsAround() throws IOException { JsonReader reader = new JsonReader(reader("[-22233720368547758070]")); reader.setLenient(true); reader.beginArray(); assertEquals(NUMBER, reader.peek()); try { reader.nextLong(); fail(); } catch (NumberFormatException expected) { } } /** * Issue 1053, negative zero. * @throws Exception */ public void testNegativeZero() throws Exception { JsonReader reader = new JsonReader(reader("[-0]")); reader.setLenient(false); reader.beginArray(); assertEquals(NUMBER, reader.peek()); assertEquals("-0", reader.nextString()); } /** * This test fails because there's no double for 9223372036854775808, and our * long parsing uses Double.parseDouble() for fractional values. */ public void disabled_testPeekLargerThanLongMaxValue() throws IOException { JsonReader reader = new JsonReader(reader("[9223372036854775808]")); reader.setLenient(true); reader.beginArray(); assertEquals(NUMBER, reader.peek()); try { reader.nextLong(); fail(); } catch (NumberFormatException e) { } } /** * This test fails because there's no double for -9223372036854775809, and our * long parsing uses Double.parseDouble() for fractional values. */ public void disabled_testPeekLargerThanLongMinValue() throws IOException { JsonReader reader = new JsonReader(reader("[-9223372036854775809]")); reader.setLenient(true); reader.beginArray(); assertEquals(NUMBER, reader.peek()); try { reader.nextLong(); fail(); } catch (NumberFormatException expected) { } assertEquals(-9223372036854775809d, reader.nextDouble()); } /** * This test fails because there's no double for 9223372036854775806, and * our long parsing uses Double.parseDouble() for fractional values. */ public void disabled_testHighPrecisionLong() throws IOException { String json = "[9223372036854775806.000]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); assertEquals(9223372036854775806L, reader.nextLong()); reader.endArray(); } public void testPeekMuchLargerThanLongMinValue() throws IOException { JsonReader reader = new JsonReader(reader("[-92233720368547758080]")); reader.setLenient(true); reader.beginArray(); assertEquals(NUMBER, reader.peek()); try { reader.nextLong(); fail(); } catch (NumberFormatException expected) { } assertEquals(-92233720368547758080d, reader.nextDouble()); } public void testQuotedNumberWithEscape() throws IOException { JsonReader reader = new JsonReader(reader("[\"12\u00334\"]")); reader.setLenient(true); reader.beginArray(); assertEquals(STRING, reader.peek()); assertEquals(1234, reader.nextInt()); } public void testMixedCaseLiterals() throws IOException { JsonReader reader = new JsonReader(reader("[True,TruE,False,FALSE,NULL,nulL]")); reader.beginArray(); assertEquals(true, reader.nextBoolean()); assertEquals(true, reader.nextBoolean()); assertEquals(false, reader.nextBoolean()); assertEquals(false, reader.nextBoolean()); reader.nextNull(); reader.nextNull(); reader.endArray(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testMissingValue() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":}")); reader.beginObject(); assertEquals("a", reader.nextName()); try { reader.nextString(); fail(); } catch (IOException expected) { } } public void testPrematureEndOfInput() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":true,")); reader.beginObject(); assertEquals("a", reader.nextName()); assertEquals(true, reader.nextBoolean()); try { reader.nextName(); fail(); } catch (IOException expected) { } } public void testPrematurelyClosed() throws IOException { try { JsonReader reader = new JsonReader(reader("{\"a\":[]}")); reader.beginObject(); reader.close(); reader.nextName(); fail(); } catch (IllegalStateException expected) { } try { JsonReader reader = new JsonReader(reader("{\"a\":[]}")); reader.close(); reader.beginObject(); fail(); } catch (IllegalStateException expected) { } try { JsonReader reader = new JsonReader(reader("{\"a\":true}")); reader.beginObject(); reader.nextName(); reader.peek(); reader.close(); reader.nextBoolean(); fail(); } catch (IllegalStateException expected) { } } public void testNextFailuresDoNotAdvance() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":true}")); reader.beginObject(); try { reader.nextString(); fail(); } catch (IllegalStateException expected) { } assertEquals("a", reader.nextName()); try { reader.nextName(); fail(); } catch (IllegalStateException expected) { } try { reader.beginArray(); fail(); } catch (IllegalStateException expected) { } try { reader.endArray(); fail(); } catch (IllegalStateException expected) { } try { reader.beginObject(); fail(); } catch (IllegalStateException expected) { } try { reader.endObject(); fail(); } catch (IllegalStateException expected) { } assertEquals(true, reader.nextBoolean()); try { reader.nextString(); fail(); } catch (IllegalStateException expected) { } try { reader.nextName(); fail(); } catch (IllegalStateException expected) { } try { reader.beginArray(); fail(); } catch (IllegalStateException expected) { } try { reader.endArray(); fail(); } catch (IllegalStateException expected) { } reader.endObject(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); reader.close(); } public void testIntegerMismatchFailuresDoNotAdvance() throws IOException { JsonReader reader = new JsonReader(reader("[1.5]")); reader.beginArray(); try { reader.nextInt(); fail(); } catch (NumberFormatException expected) { } assertEquals(1.5d, reader.nextDouble()); reader.endArray(); } public void testStringNullIsNotNull() throws IOException { JsonReader reader = new JsonReader(reader("[\"null\"]")); reader.beginArray(); try { reader.nextNull(); fail(); } catch (IllegalStateException expected) { } } public void testNullLiteralIsNotAString() throws IOException { JsonReader reader = new JsonReader(reader("[null]")); reader.beginArray(); try { reader.nextString(); fail(); } catch (IllegalStateException expected) { } } public void testStrictNameValueSeparator() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\"=true}")); reader.beginObject(); assertEquals("a", reader.nextName()); try { reader.nextBoolean(); fail(); } catch (IOException expected) { } reader = new JsonReader(reader("{\"a\"=>true}")); reader.beginObject(); assertEquals("a", reader.nextName()); try { reader.nextBoolean(); fail(); } catch (IOException expected) { } } public void testLenientNameValueSeparator() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\"=true}")); reader.setLenient(true); reader.beginObject(); assertEquals("a", reader.nextName()); assertEquals(true, reader.nextBoolean()); reader = new JsonReader(reader("{\"a\"=>true}")); reader.setLenient(true); reader.beginObject(); assertEquals("a", reader.nextName()); assertEquals(true, reader.nextBoolean()); } public void testStrictNameValueSeparatorWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\"=true}")); reader.beginObject(); assertEquals("a", reader.nextName()); try { reader.skipValue(); fail(); } catch (IOException expected) { } reader = new JsonReader(reader("{\"a\"=>true}")); reader.beginObject(); assertEquals("a", reader.nextName()); try { reader.skipValue(); fail(); } catch (IOException expected) { } } public void testCommentsInStringValue() throws Exception { JsonReader reader = new JsonReader(reader("[\"// comment\"]")); reader.beginArray(); assertEquals("// comment", reader.nextString()); reader.endArray(); reader = new JsonReader(reader("{\"a\":\"#someComment\"}")); reader.beginObject(); assertEquals("a", reader.nextName()); assertEquals("#someComment", reader.nextString()); reader.endObject(); reader = new JsonReader(reader("{\"#//a\":\"#some //Comment\"}")); reader.beginObject(); assertEquals("#//a", reader.nextName()); assertEquals("#some //Comment", reader.nextString()); reader.endObject(); } public void testStrictComments() throws IOException { JsonReader reader = new JsonReader(reader("[// comment \n true]")); reader.beginArray(); try { reader.nextBoolean(); fail(); } catch (IOException expected) { } reader = new JsonReader(reader("[# comment \n true]")); reader.beginArray(); try { reader.nextBoolean(); fail(); } catch (IOException expected) { } reader = new JsonReader(reader("[/* comment */ true]")); reader.beginArray(); try { reader.nextBoolean(); fail(); } catch (IOException expected) { } } public void testLenientComments() throws IOException { JsonReader reader = new JsonReader(reader("[// comment \n true]")); reader.setLenient(true); reader.beginArray(); assertEquals(true, reader.nextBoolean()); reader = new JsonReader(reader("[# comment \n true]")); reader.setLenient(true); reader.beginArray(); assertEquals(true, reader.nextBoolean()); reader = new JsonReader(reader("[/* comment */ true]")); reader.setLenient(true); reader.beginArray(); assertEquals(true, reader.nextBoolean()); } public void testStrictCommentsWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("[// comment \n true]")); reader.beginArray(); try { reader.skipValue(); fail(); } catch (IOException expected) { } reader = new JsonReader(reader("[# comment \n true]")); reader.beginArray(); try { reader.skipValue(); fail(); } catch (IOException expected) { } reader = new JsonReader(reader("[/* comment */ true]")); reader.beginArray(); try { reader.skipValue(); fail(); } catch (IOException expected) { } } public void testStrictUnquotedNames() throws IOException { JsonReader reader = new JsonReader(reader("{a:true}")); reader.beginObject(); try { reader.nextName(); fail(); } catch (IOException expected) { } } public void testLenientUnquotedNames() throws IOException { JsonReader reader = new JsonReader(reader("{a:true}")); reader.setLenient(true); reader.beginObject(); assertEquals("a", reader.nextName()); } public void testStrictUnquotedNamesWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("{a:true}")); reader.beginObject(); try { reader.skipValue(); fail(); } catch (IOException expected) { } } public void testStrictSingleQuotedNames() throws IOException { JsonReader reader = new JsonReader(reader("{'a':true}")); reader.beginObject(); try { reader.nextName(); fail(); } catch (IOException expected) { } } public void testLenientSingleQuotedNames() throws IOException { JsonReader reader = new JsonReader(reader("{'a':true}")); reader.setLenient(true); reader.beginObject(); assertEquals("a", reader.nextName()); } public void testStrictSingleQuotedNamesWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("{'a':true}")); reader.beginObject(); try { reader.skipValue(); fail(); } catch (IOException expected) { } } public void testStrictUnquotedStrings() throws IOException { JsonReader reader = new JsonReader(reader("[a]")); reader.beginArray(); try { reader.nextString(); fail(); } catch (MalformedJsonException expected) { } } public void testStrictUnquotedStringsWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("[a]")); reader.beginArray(); try { reader.skipValue(); fail(); } catch (MalformedJsonException expected) { } } public void testLenientUnquotedStrings() throws IOException { JsonReader reader = new JsonReader(reader("[a]")); reader.setLenient(true); reader.beginArray(); assertEquals("a", reader.nextString()); } public void testStrictSingleQuotedStrings() throws IOException { JsonReader reader = new JsonReader(reader("['a']")); reader.beginArray(); try { reader.nextString(); fail(); } catch (IOException expected) { } } public void testLenientSingleQuotedStrings() throws IOException { JsonReader reader = new JsonReader(reader("['a']")); reader.setLenient(true); reader.beginArray(); assertEquals("a", reader.nextString()); } public void testStrictSingleQuotedStringsWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("['a']")); reader.beginArray(); try { reader.skipValue(); fail(); } catch (IOException expected) { } } public void testStrictSemicolonDelimitedArray() throws IOException { JsonReader reader = new JsonReader(reader("[true;true]")); reader.beginArray(); try { reader.nextBoolean(); reader.nextBoolean(); fail(); } catch (IOException expected) { } } public void testLenientSemicolonDelimitedArray() throws IOException { JsonReader reader = new JsonReader(reader("[true;true]")); reader.setLenient(true); reader.beginArray(); assertEquals(true, reader.nextBoolean()); assertEquals(true, reader.nextBoolean()); } public void testStrictSemicolonDelimitedArrayWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("[true;true]")); reader.beginArray(); try { reader.skipValue(); reader.skipValue(); fail(); } catch (IOException expected) { } } public void testStrictSemicolonDelimitedNameValuePair() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":true;\"b\":true}")); reader.beginObject(); assertEquals("a", reader.nextName()); try { reader.nextBoolean(); reader.nextName(); fail(); } catch (IOException expected) { } } public void testLenientSemicolonDelimitedNameValuePair() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":true;\"b\":true}")); reader.setLenient(true); reader.beginObject(); assertEquals("a", reader.nextName()); assertEquals(true, reader.nextBoolean()); assertEquals("b", reader.nextName()); } public void testStrictSemicolonDelimitedNameValuePairWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":true;\"b\":true}")); reader.beginObject(); assertEquals("a", reader.nextName()); try { reader.skipValue(); reader.skipValue(); fail(); } catch (IOException expected) { } } public void testStrictUnnecessaryArraySeparators() throws IOException { JsonReader reader = new JsonReader(reader("[true,,true]")); reader.beginArray(); assertEquals(true, reader.nextBoolean()); try { reader.nextNull(); fail(); } catch (IOException expected) { } reader = new JsonReader(reader("[,true]")); reader.beginArray(); try { reader.nextNull(); fail(); } catch (IOException expected) { } reader = new JsonReader(reader("[true,]")); reader.beginArray(); assertEquals(true, reader.nextBoolean()); try { reader.nextNull(); fail(); } catch (IOException expected) { } reader = new JsonReader(reader("[,]")); reader.beginArray(); try { reader.nextNull(); fail(); } catch (IOException expected) { } } public void testLenientUnnecessaryArraySeparators() throws IOException { JsonReader reader = new JsonReader(reader("[true,,true]")); reader.setLenient(true); reader.beginArray(); assertEquals(true, reader.nextBoolean()); reader.nextNull(); assertEquals(true, reader.nextBoolean()); reader.endArray(); reader = new JsonReader(reader("[,true]")); reader.setLenient(true); reader.beginArray(); reader.nextNull(); assertEquals(true, reader.nextBoolean()); reader.endArray(); reader = new JsonReader(reader("[true,]")); reader.setLenient(true); reader.beginArray(); assertEquals(true, reader.nextBoolean()); reader.nextNull(); reader.endArray(); reader = new JsonReader(reader("[,]")); reader.setLenient(true); reader.beginArray(); reader.nextNull(); reader.nextNull(); reader.endArray(); } public void testStrictUnnecessaryArraySeparatorsWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("[true,,true]")); reader.beginArray(); assertEquals(true, reader.nextBoolean()); try { reader.skipValue(); fail(); } catch (IOException expected) { } reader = new JsonReader(reader("[,true]")); reader.beginArray(); try { reader.skipValue(); fail(); } catch (IOException expected) { } reader = new JsonReader(reader("[true,]")); reader.beginArray(); assertEquals(true, reader.nextBoolean()); try { reader.skipValue(); fail(); } catch (IOException expected) { } reader = new JsonReader(reader("[,]")); reader.beginArray(); try { reader.skipValue(); fail(); } catch (IOException expected) { } } public void testStrictMultipleTopLevelValues() throws IOException { JsonReader reader = new JsonReader(reader("[] []")); reader.beginArray(); reader.endArray(); try { reader.peek(); fail(); } catch (IOException expected) { } } public void testLenientMultipleTopLevelValues() throws IOException { JsonReader reader = new JsonReader(reader("[] true {}")); reader.setLenient(true); reader.beginArray(); reader.endArray(); assertEquals(true, reader.nextBoolean()); reader.beginObject(); reader.endObject(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testStrictMultipleTopLevelValuesWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("[] []")); reader.beginArray(); reader.endArray(); try { reader.skipValue(); fail(); } catch (IOException expected) { } } public void testTopLevelValueTypes() throws IOException { JsonReader reader1 = new JsonReader(reader("true")); assertTrue(reader1.nextBoolean()); assertEquals(JsonToken.END_DOCUMENT, reader1.peek()); JsonReader reader2 = new JsonReader(reader("false")); assertFalse(reader2.nextBoolean()); assertEquals(JsonToken.END_DOCUMENT, reader2.peek()); JsonReader reader3 = new JsonReader(reader("null")); assertEquals(JsonToken.NULL, reader3.peek()); reader3.nextNull(); assertEquals(JsonToken.END_DOCUMENT, reader3.peek()); JsonReader reader4 = new JsonReader(reader("123")); assertEquals(123, reader4.nextInt()); assertEquals(JsonToken.END_DOCUMENT, reader4.peek()); JsonReader reader5 = new JsonReader(reader("123.4")); assertEquals(123.4, reader5.nextDouble()); assertEquals(JsonToken.END_DOCUMENT, reader5.peek()); JsonReader reader6 = new JsonReader(reader("\"a\"")); assertEquals("a", reader6.nextString()); assertEquals(JsonToken.END_DOCUMENT, reader6.peek()); } public void testTopLevelValueTypeWithSkipValue() throws IOException { JsonReader reader = new JsonReader(reader("true")); reader.skipValue(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testStrictNonExecutePrefix() { JsonReader reader = new JsonReader(reader(")]}'\n []")); try { reader.beginArray(); fail(); } catch (IOException expected) { } } public void testStrictNonExecutePrefixWithSkipValue() { JsonReader reader = new JsonReader(reader(")]}'\n []")); try { reader.skipValue(); fail(); } catch (IOException expected) { } } public void testLenientNonExecutePrefix() throws IOException { JsonReader reader = new JsonReader(reader(")]}'\n []")); reader.setLenient(true); reader.beginArray(); reader.endArray(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testLenientNonExecutePrefixWithLeadingWhitespace() throws IOException { JsonReader reader = new JsonReader(reader("\r\n \t)]}'\n []")); reader.setLenient(true); reader.beginArray(); reader.endArray(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testLenientPartialNonExecutePrefix() { JsonReader reader = new JsonReader(reader(")]}' []")); reader.setLenient(true); try { assertEquals(")", reader.nextString()); reader.nextString(); fail(); } catch (IOException expected) { } } public void testBomIgnoredAsFirstCharacterOfDocument() throws IOException { JsonReader reader = new JsonReader(reader("\ufeff[]")); reader.beginArray(); reader.endArray(); } public void testBomForbiddenAsOtherCharacterInDocument() throws IOException { JsonReader reader = new JsonReader(reader("[\ufeff]")); reader.beginArray(); try { reader.endArray(); fail(); } catch (IOException expected) { } } public void testFailWithPosition() throws IOException { testFailWithPosition("Expected value at line 6 column 5 path $[1]", "[\n\n\n\n\n\"a\",}]"); } public void testFailWithPositionGreaterThanBufferSize() throws IOException { String spaces = repeat(' ', 8192); testFailWithPosition("Expected value at line 6 column 5 path $[1]", "[\n\n" + spaces + "\n\n\n\"a\",}]"); } public void testFailWithPositionOverSlashSlashEndOfLineComment() throws IOException { testFailWithPosition("Expected value at line 5 column 6 path $[1]", "\n// foo\n\n//bar\r\n[\"a\",}"); } public void testFailWithPositionOverHashEndOfLineComment() throws IOException { testFailWithPosition("Expected value at line 5 column 6 path $[1]", "\n# foo\n\n#bar\r\n[\"a\",}"); } public void testFailWithPositionOverCStyleComment() throws IOException { testFailWithPosition("Expected value at line 6 column 12 path $[1]", "\n\n/* foo\n*\n*\r\nbar */[\"a\",}"); } public void testFailWithPositionOverQuotedString() throws IOException { testFailWithPosition("Expected value at line 5 column 3 path $[1]", "[\"foo\nbar\r\nbaz\n\",\n }"); } public void testFailWithPositionOverUnquotedString() throws IOException { testFailWithPosition("Expected value at line 5 column 2 path $[1]", "[\n\nabcd\n\n,}"); } public void testFailWithEscapedNewlineCharacter() throws IOException { testFailWithPosition("Expected value at line 5 column 3 path $[1]", "[\n\n\"\\\n\n\",}"); } public void testFailWithPositionIsOffsetByBom() throws IOException { testFailWithPosition("Expected value at line 1 column 6 path $[1]", "\ufeff[\"a\",}]"); } private void testFailWithPosition(String message, String json) throws IOException { // Validate that it works reading the string normally. JsonReader reader1 = new JsonReader(reader(json)); reader1.setLenient(true); reader1.beginArray(); reader1.nextString(); try { reader1.peek(); fail(); } catch (IOException expected) { assertEquals(message, expected.getMessage()); } // Also validate that it works when skipping. JsonReader reader2 = new JsonReader(reader(json)); reader2.setLenient(true); reader2.beginArray(); reader2.skipValue(); try { reader2.peek(); fail(); } catch (IOException expected) { assertEquals(message, expected.getMessage()); } } public void testFailWithPositionDeepPath() throws IOException { JsonReader reader = new JsonReader(reader("[1,{\"a\":[2,3,}")); reader.beginArray(); reader.nextInt(); reader.beginObject(); reader.nextName(); reader.beginArray(); reader.nextInt(); reader.nextInt(); try { reader.peek(); fail(); } catch (IOException expected) { assertEquals("Expected value at line 1 column 14 path $[1].a[2]", expected.getMessage()); } } public void testStrictVeryLongNumber() throws IOException { JsonReader reader = new JsonReader(reader("[0." + repeat('9', 8192) + "]")); reader.beginArray(); try { assertEquals(1d, reader.nextDouble()); fail(); } catch (MalformedJsonException expected) { } } public void testLenientVeryLongNumber() throws IOException { JsonReader reader = new JsonReader(reader("[0." + repeat('9', 8192) + "]")); reader.setLenient(true); reader.beginArray(); assertEquals(JsonToken.STRING, reader.peek()); assertEquals(1d, reader.nextDouble()); reader.endArray(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testVeryLongUnquotedLiteral() throws IOException { String literal = "a" + repeat('b', 8192) + "c"; JsonReader reader = new JsonReader(reader("[" + literal + "]")); reader.setLenient(true); reader.beginArray(); assertEquals(literal, reader.nextString()); reader.endArray(); } public void testDeeplyNestedArrays() throws IOException { // this is nested 40 levels deep; Gson is tuned for nesting is 30 levels deep or fewer JsonReader reader = new JsonReader(reader( "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]")); for (int i = 0; i < 40; i++) { reader.beginArray(); } assertEquals("$[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0]" + "[0][0][0][0][0][0][0][0][0][0][0][0][0][0]", reader.getPath()); for (int i = 0; i < 40; i++) { reader.endArray(); } assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testDeeplyNestedObjects() throws IOException { // Build a JSON document structured like {"a":{"a":{"a":{"a":true}}}}, but 40 levels deep String array = "{\"a\":%s}"; String json = "true"; for (int i = 0; i < 40; i++) { json = String.format(array, json); } JsonReader reader = new JsonReader(reader(json)); for (int i = 0; i < 40; i++) { reader.beginObject(); assertEquals("a", reader.nextName()); } assertEquals("$.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a" + ".a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a", reader.getPath()); assertEquals(true, reader.nextBoolean()); for (int i = 0; i < 40; i++) { reader.endObject(); } assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } // http://code.google.com/p/google-gson/issues/detail?id=409 public void testStringEndingInSlash() throws IOException { JsonReader reader = new JsonReader(reader("/")); reader.setLenient(true); try { reader.peek(); fail(); } catch (MalformedJsonException expected) { } } public void testDocumentWithCommentEndingInSlash() throws IOException { JsonReader reader = new JsonReader(reader("/* foo *//")); reader.setLenient(true); try { reader.peek(); fail(); } catch (MalformedJsonException expected) { } } public void testStringWithLeadingSlash() throws IOException { JsonReader reader = new JsonReader(reader("/x")); reader.setLenient(true); try { reader.peek(); fail(); } catch (MalformedJsonException expected) { } } public void testUnterminatedObject() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":\"android\"x")); reader.setLenient(true); reader.beginObject(); assertEquals("a", reader.nextName()); assertEquals("android", reader.nextString()); try { reader.peek(); fail(); } catch (MalformedJsonException expected) { } } public void testVeryLongQuotedString() throws IOException { char[] stringChars = new char[1024 * 16]; Arrays.fill(stringChars, 'x'); String string = new String(stringChars); String json = "[\"" + string + "\"]"; JsonReader reader = new JsonReader(reader(json)); reader.beginArray(); assertEquals(string, reader.nextString()); reader.endArray(); } public void testVeryLongUnquotedString() throws IOException { char[] stringChars = new char[1024 * 16]; Arrays.fill(stringChars, 'x'); String string = new String(stringChars); String json = "[" + string + "]"; JsonReader reader = new JsonReader(reader(json)); reader.setLenient(true); reader.beginArray(); assertEquals(string, reader.nextString()); reader.endArray(); } public void testVeryLongUnterminatedString() throws IOException { char[] stringChars = new char[1024 * 16]; Arrays.fill(stringChars, 'x'); String string = new String(stringChars); String json = "[" + string; JsonReader reader = new JsonReader(reader(json)); reader.setLenient(true); reader.beginArray(); assertEquals(string, reader.nextString()); try { reader.peek(); fail(); } catch (EOFException expected) { } } public void testSkipVeryLongUnquotedString() throws IOException { JsonReader reader = new JsonReader(reader("[" + repeat('x', 8192) + "]")); reader.setLenient(true); reader.beginArray(); reader.skipValue(); reader.endArray(); } public void testSkipTopLevelUnquotedString() throws IOException { JsonReader reader = new JsonReader(reader(repeat('x', 8192))); reader.setLenient(true); reader.skipValue(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testSkipVeryLongQuotedString() throws IOException { JsonReader reader = new JsonReader(reader("[\"" + repeat('x', 8192) + "\"]")); reader.beginArray(); reader.skipValue(); reader.endArray(); } public void testSkipTopLevelQuotedString() throws IOException { JsonReader reader = new JsonReader(reader("\"" + repeat('x', 8192) + "\"")); reader.setLenient(true); reader.skipValue(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testStringAsNumberWithTruncatedExponent() throws IOException { JsonReader reader = new JsonReader(reader("[123e]")); reader.setLenient(true); reader.beginArray(); assertEquals(STRING, reader.peek()); } public void testStringAsNumberWithDigitAndNonDigitExponent() throws IOException { JsonReader reader = new JsonReader(reader("[123e4b]")); reader.setLenient(true); reader.beginArray(); assertEquals(STRING, reader.peek()); } public void testStringAsNumberWithNonDigitExponent() throws IOException { JsonReader reader = new JsonReader(reader("[123eb]")); reader.setLenient(true); reader.beginArray(); assertEquals(STRING, reader.peek()); } public void testEmptyStringName() throws IOException { JsonReader reader = new JsonReader(reader("{\"\":true}")); reader.setLenient(true); assertEquals(BEGIN_OBJECT, reader.peek()); reader.beginObject(); assertEquals(NAME, reader.peek()); assertEquals("", reader.nextName()); assertEquals(JsonToken.BOOLEAN, reader.peek()); assertEquals(true, reader.nextBoolean()); assertEquals(JsonToken.END_OBJECT, reader.peek()); reader.endObject(); assertEquals(JsonToken.END_DOCUMENT, reader.peek()); } public void testStrictExtraCommasInMaps() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":\"b\",}")); reader.beginObject(); assertEquals("a", reader.nextName()); assertEquals("b", reader.nextString()); try { reader.peek(); fail(); } catch (IOException expected) { } } public void testLenientExtraCommasInMaps() throws IOException { JsonReader reader = new JsonReader(reader("{\"a\":\"b\",}")); reader.setLenient(true); reader.beginObject(); assertEquals("a", reader.nextName()); assertEquals("b", reader.nextString()); try { reader.peek(); fail(); } catch (IOException expected) { } } private String repeat(char c, int count) { char[] array = new char[count]; Arrays.fill(array, c); return new String(array); } public void testMalformedDocuments() throws IOException { assertDocument("{]", BEGIN_OBJECT, IOException.class); assertDocument("{,", BEGIN_OBJECT, IOException.class); assertDocument("{{", BEGIN_OBJECT, IOException.class); assertDocument("{[", BEGIN_OBJECT, IOException.class); assertDocument("{:", BEGIN_OBJECT, IOException.class); assertDocument("{\"name\",", BEGIN_OBJECT, NAME, IOException.class); assertDocument("{\"name\",", BEGIN_OBJECT, NAME, IOException.class); assertDocument("{\"name\":}", BEGIN_OBJECT, NAME, IOException.class); assertDocument("{\"name\"::", BEGIN_OBJECT, NAME, IOException.class); assertDocument("{\"name\":,", BEGIN_OBJECT, NAME, IOException.class); assertDocument("{\"name\"=}", BEGIN_OBJECT, NAME, IOException.class); assertDocument("{\"name\"=>}", BEGIN_OBJECT, NAME, IOException.class); assertDocument("{\"name\"=>\"string\":", BEGIN_OBJECT, NAME, STRING, IOException.class); assertDocument("{\"name\"=>\"string\"=", BEGIN_OBJECT, NAME, STRING, IOException.class); assertDocument("{\"name\"=>\"string\"=>", BEGIN_OBJECT, NAME, STRING, IOException.class); assertDocument("{\"name\"=>\"string\",", BEGIN_OBJECT, NAME, STRING, IOException.class); assertDocument("{\"name\"=>\"string\",\"name\"", BEGIN_OBJECT, NAME, STRING, NAME); assertDocument("[}", BEGIN_ARRAY, IOException.class); assertDocument("[,]", BEGIN_ARRAY, NULL, NULL, END_ARRAY); assertDocument("{", BEGIN_OBJECT, IOException.class); assertDocument("{\"name\"", BEGIN_OBJECT, NAME, IOException.class); assertDocument("{\"name\",", BEGIN_OBJECT, NAME, IOException.class); assertDocument("{'name'", BEGIN_OBJECT, NAME, IOException.class); assertDocument("{'name',", BEGIN_OBJECT, NAME, IOException.class); assertDocument("{name", BEGIN_OBJECT, NAME, IOException.class); assertDocument("[", BEGIN_ARRAY, IOException.class); assertDocument("[string", BEGIN_ARRAY, STRING, IOException.class); assertDocument("[\"string\"", BEGIN_ARRAY, STRING, IOException.class); assertDocument("['string'", BEGIN_ARRAY, STRING, IOException.class); assertDocument("[123", BEGIN_ARRAY, NUMBER, IOException.class); assertDocument("[123,", BEGIN_ARRAY, NUMBER, IOException.class); assertDocument("{\"name\":123", BEGIN_OBJECT, NAME, NUMBER, IOException.class); assertDocument("{\"name\":123,", BEGIN_OBJECT, NAME, NUMBER, IOException.class); assertDocument("{\"name\":\"string\"", BEGIN_OBJECT, NAME, STRING, IOException.class); assertDocument("{\"name\":\"string\",", BEGIN_OBJECT, NAME, STRING, IOException.class); assertDocument("{\"name\":'string'", BEGIN_OBJECT, NAME, STRING, IOException.class); assertDocument("{\"name\":'string',", BEGIN_OBJECT, NAME, STRING, IOException.class); assertDocument("{\"name\":false", BEGIN_OBJECT, NAME, BOOLEAN, IOException.class); assertDocument("{\"name\":false,,", BEGIN_OBJECT, NAME, BOOLEAN, IOException.class); } /** * This test behave slightly differently in Gson 2.2 and earlier. It fails * during peek rather than during nextString(). */ public void testUnterminatedStringFailure() throws IOException { JsonReader reader = new JsonReader(reader("[\"string")); reader.setLenient(true); reader.beginArray(); assertEquals(JsonToken.STRING, reader.peek()); try { reader.nextString(); fail(); } catch (MalformedJsonException expected) { } } private void assertDocument(String document, Object... expectations) throws IOException { JsonReader reader = new JsonReader(reader(document)); reader.setLenient(true); for (Object expectation : expectations) { if (expectation == BEGIN_OBJECT) { reader.beginObject(); } else if (expectation == BEGIN_ARRAY) { reader.beginArray(); } else if (expectation == END_OBJECT) { reader.endObject(); } else if (expectation == END_ARRAY) { reader.endArray(); } else if (expectation == NAME) { assertEquals("name", reader.nextName()); } else if (expectation == BOOLEAN) { assertEquals(false, reader.nextBoolean()); } else if (expectation == STRING) { assertEquals("string", reader.nextString()); } else if (expectation == NUMBER) { assertEquals(123, reader.nextInt()); } else if (expectation == NULL) { reader.nextNull(); } else if (expectation == IOException.class) { try { reader.peek(); fail(); } catch (IOException expected) { } } else { throw new AssertionError(); } } } /** * Returns a reader that returns one character at a time. */ private Reader reader(final String s) { /* if (true) */ return new StringReader(s); /* return new Reader() { int position = 0; @Override public int read(char[] buffer, int offset, int count) throws IOException { if (position == s.length()) { return -1; } else if (count > 0) { buffer[offset] = s.charAt(position++); return 1; } else { throw new IllegalArgumentException(); } } @Override public void close() throws IOException { } }; */ } }
[ { "be_test_class_file": "com/google/gson/stream/JsonReader.java", "be_test_class_name": "com.google.gson.stream.JsonReader", "be_test_function_name": "beginArray", "be_test_function_signature": "()V", "line_numbers": [ "341", "342", "343", "345", "346", "347", "348", "350", "352" ], "method_line_rate": 0.8888888888888888 }, { "be_test_class_file": "com/google/gson/stream/JsonReader.java", "be_test_class_name": "com.google.gson.stream.JsonReader", "be_test_function_name": "consumeNonExecutePrefix", "be_test_function_signature": "()V", "line_numbers": [ "1576", "1577", "1579", "1580", "1583", "1584", "1585", "1590", "1591" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "com/google/gson/stream/JsonReader.java", "be_test_class_name": "com.google.gson.stream.JsonReader", "be_test_function_name": "doPeek", "be_test_function_signature": "()I", "line_numbers": [ "462", "463", "464", "465", "467", "468", "470", "472", "474", "476", "478", "479", "481", "482", "483", "485", "487", "489", "491", "494", "495", "497", "499", "500", "502", "503", "505", "508", "509", "510", "511", "513", "516", "517", "519", "520", "522", "524", "525", "526", "530", "532", "533", "534", "536", "537", "538", "539", "540", "542", "543", "545", "546", "549", "550", "552", "553", "559", "560", "561", "562", "564", "567", "568", "570", "572", "574", "576", "579", "580", "581", "584", "585", "586", "589", "590", "593", "594" ], "method_line_rate": 0.15384615384615385 }, { "be_test_class_file": "com/google/gson/stream/JsonReader.java", "be_test_class_name": "com.google.gson.stream.JsonReader", "be_test_function_name": "fillBuffer", "be_test_function_signature": "(I)Z", "line_numbers": [ "1284", "1285", "1286", "1287", "1288", "1290", "1293", "1295", "1296", "1299", "1300", "1301", "1302", "1305", "1306", "1309" ], "method_line_rate": 0.6875 }, { "be_test_class_file": "com/google/gson/stream/JsonReader.java", "be_test_class_name": "com.google.gson.stream.JsonReader", "be_test_function_name": "getPath", "be_test_function_signature": "()Ljava/lang/String;", "line_numbers": [ "1468", "1469", "1470", "1473", "1474", "1479", "1480", "1481", "1491" ], "method_line_rate": 0.6666666666666666 }, { "be_test_class_file": "com/google/gson/stream/JsonReader.java", "be_test_class_name": "com.google.gson.stream.JsonReader", "be_test_function_name": "locationString", "be_test_function_signature": "()Ljava/lang/String;", "line_numbers": [ "1458", "1459", "1460" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/gson/stream/JsonReader.java", "be_test_class_name": "com.google.gson.stream.JsonReader", "be_test_function_name": "nextNonWhitespace", "be_test_function_signature": "(Z)I", "line_numbers": [ "1327", "1328", "1329", "1331", "1332", "1333", "1334", "1336", "1337", "1340", "1341", "1342", "1343", "1344", "1345", "1346", "1349", "1350", "1351", "1352", "1353", "1354", "1355", "1356", "1360", "1361", "1362", "1365", "1366", "1367", "1369", "1370", "1371", "1375", "1376", "1377", "1378", "1379", "1382", "1384", "1385", "1391", "1392", "1393", "1394", "1396", "1397", "1399", "1400", "1401", "1403" ], "method_line_rate": 0.29411764705882354 }, { "be_test_class_file": "com/google/gson/stream/JsonReader.java", "be_test_class_name": "com.google.gson.stream.JsonReader", "be_test_function_name": "nextQuotedValue", "be_test_function_signature": "(C)Ljava/lang/String;", "line_numbers": [ "987", "988", "990", "991", "993", "994", "995", "997", "998", "999", "1000", "1001", "1003", "1004", "1006", "1007", "1008", "1009", "1010", "1011", "1013", "1014", "1015", "1016", "1017", "1018", "1019", "1020", "1022", "1024", "1025", "1026", "1028", "1029", "1030", "1031", "1033" ], "method_line_rate": 0.4594594594594595 }, { "be_test_class_file": "com/google/gson/stream/JsonReader.java", "be_test_class_name": "com.google.gson.stream.JsonReader", "be_test_function_name": "nextString", "be_test_function_signature": "()Ljava/lang/String;", "line_numbers": [ "805", "806", "807", "810", "811", "812", "813", "814", "815", "816", "817", "818", "819", "820", "821", "822", "823", "825", "827", "828", "829" ], "method_line_rate": 0.2857142857142857 }, { "be_test_class_file": "com/google/gson/stream/JsonReader.java", "be_test_class_name": "com.google.gson.stream.JsonReader", "be_test_function_name": "peek", "be_test_function_signature": "()Lcom/google/gson/stream/JsonToken;", "line_numbers": [ "423", "424", "425", "428", "430", "432", "434", "436", "440", "443", "445", "450", "453", "455", "457" ], "method_line_rate": 0.3333333333333333 }, { "be_test_class_file": "com/google/gson/stream/JsonReader.java", "be_test_class_name": "com.google.gson.stream.JsonReader", "be_test_function_name": "push", "be_test_function_signature": "(I)V", "line_numbers": [ "1264", "1265", "1266", "1267", "1268", "1269", "1270", "1271", "1272", "1273", "1275", "1276" ], "method_line_rate": 0.25 }, { "be_test_class_file": "com/google/gson/stream/JsonReader.java", "be_test_class_name": "com.google.gson.stream.JsonReader", "be_test_function_name": "setLenient", "be_test_function_signature": "(Z)V", "line_numbers": [ "326", "327" ], "method_line_rate": 1 }, { "be_test_class_file": "com/google/gson/stream/JsonReader.java", "be_test_class_name": "com.google.gson.stream.JsonReader", "be_test_function_name": "syntaxError", "be_test_function_signature": "(Ljava/lang/String;)Ljava/io/IOException;", "line_numbers": [ "1568" ], "method_line_rate": 1 } ]
public class Caverphone1Test extends StringEncoderAbstractTest<Caverphone1>
@Test public void testCaverphoneRevisitedCommonCodeAT1111() throws EncoderException { this.checkEncodingVariations("AT1111", new String[]{ "add", "aid", "at", "art", "eat", "earth", "head", "hit", "hot", "hold", "hard", "heart", "it", "out", "old"}); }
// // Abstract Java Tested Class // package org.apache.commons.codec.language; // // // // public class Caverphone1 extends AbstractCaverphone { // private static final String SIX_1 = "111111"; // // @Override // public String encode(final String source); // } // // // 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 Caverphone1Test extends StringEncoderAbstractTest<Caverphone1> { // // // @Override // protected Caverphone1 createStringEncoder(); // @Test // public void testCaverphoneRevisitedCommonCodeAT1111() throws EncoderException; // @Test // public void testEndMb() throws EncoderException; // @Test // public void testIsCaverphoneEquals() throws EncoderException; // @Test // public void testSpecificationV1Examples() throws EncoderException; // @Test // public void testWikipediaExamples() throws EncoderException; // } // You are a professional Java test case writer, please create a test case named `testCaverphoneRevisitedCommonCodeAT1111` for the `Caverphone1` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests example adapted from version 2.0 http://caversham.otago.ac.nz/files/working/ctp150804.pdf * * AT1111 words: add, aid, at, art, eat, earth, head, hit, hot, hold, hard, heart, it, out, old * * @throws EncoderException */
src/test/java/org/apache/commons/codec/language/Caverphone1Test.java
package org.apache.commons.codec.language;
@Override public String encode(final String source);
62
testCaverphoneRevisitedCommonCodeAT1111
```java // Abstract Java Tested Class package org.apache.commons.codec.language; public class Caverphone1 extends AbstractCaverphone { private static final String SIX_1 = "111111"; @Override public String encode(final String source); } // 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 Caverphone1Test extends StringEncoderAbstractTest<Caverphone1> { @Override protected Caverphone1 createStringEncoder(); @Test public void testCaverphoneRevisitedCommonCodeAT1111() throws EncoderException; @Test public void testEndMb() throws EncoderException; @Test public void testIsCaverphoneEquals() throws EncoderException; @Test public void testSpecificationV1Examples() throws EncoderException; @Test public void testWikipediaExamples() throws EncoderException; } ``` You are a professional Java test case writer, please create a test case named `testCaverphoneRevisitedCommonCodeAT1111` for the `Caverphone1` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests example adapted from version 2.0 http://caversham.otago.ac.nz/files/working/ctp150804.pdf * * AT1111 words: add, aid, at, art, eat, earth, head, hit, hot, hold, hard, heart, it, out, old * * @throws EncoderException */
44
// // Abstract Java Tested Class // package org.apache.commons.codec.language; // // // // public class Caverphone1 extends AbstractCaverphone { // private static final String SIX_1 = "111111"; // // @Override // public String encode(final String source); // } // // // 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 Caverphone1Test extends StringEncoderAbstractTest<Caverphone1> { // // // @Override // protected Caverphone1 createStringEncoder(); // @Test // public void testCaverphoneRevisitedCommonCodeAT1111() throws EncoderException; // @Test // public void testEndMb() throws EncoderException; // @Test // public void testIsCaverphoneEquals() throws EncoderException; // @Test // public void testSpecificationV1Examples() throws EncoderException; // @Test // public void testWikipediaExamples() throws EncoderException; // } // You are a professional Java test case writer, please create a test case named `testCaverphoneRevisitedCommonCodeAT1111` for the `Caverphone1` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests example adapted from version 2.0 http://caversham.otago.ac.nz/files/working/ctp150804.pdf * * AT1111 words: add, aid, at, art, eat, earth, head, hit, hot, hold, hard, heart, it, out, old * * @throws EncoderException */ @Test public void testCaverphoneRevisitedCommonCodeAT1111() throws EncoderException {
/** * Tests example adapted from version 2.0 http://caversham.otago.ac.nz/files/working/ctp150804.pdf * * AT1111 words: add, aid, at, art, eat, earth, head, hit, hot, hold, hard, heart, it, out, old * * @throws EncoderException */
18
org.apache.commons.codec.language.Caverphone1
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.codec.language; public class Caverphone1 extends AbstractCaverphone { private static final String SIX_1 = "111111"; @Override public String encode(final String source); } // 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 Caverphone1Test extends StringEncoderAbstractTest<Caverphone1> { @Override protected Caverphone1 createStringEncoder(); @Test public void testCaverphoneRevisitedCommonCodeAT1111() throws EncoderException; @Test public void testEndMb() throws EncoderException; @Test public void testIsCaverphoneEquals() throws EncoderException; @Test public void testSpecificationV1Examples() throws EncoderException; @Test public void testWikipediaExamples() throws EncoderException; } ``` You are a professional Java test case writer, please create a test case named `testCaverphoneRevisitedCommonCodeAT1111` for the `Caverphone1` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests example adapted from version 2.0 http://caversham.otago.ac.nz/files/working/ctp150804.pdf * * AT1111 words: add, aid, at, art, eat, earth, head, hit, hot, hold, hard, heart, it, out, old * * @throws EncoderException */ @Test public void testCaverphoneRevisitedCommonCodeAT1111() throws EncoderException { ```
public class Caverphone1 extends AbstractCaverphone
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;
@Override protected Caverphone1 createStringEncoder(); @Test public void testCaverphoneRevisitedCommonCodeAT1111() throws EncoderException; @Test public void testEndMb() throws EncoderException; @Test public void testIsCaverphoneEquals() throws EncoderException; @Test public void testSpecificationV1Examples() throws EncoderException; @Test public void testWikipediaExamples() throws EncoderException;
b63e55d965cbd13d4e6bd2a1f9e72a360b57f14404e95fbd7920d81a833c871e
[ "org.apache.commons.codec.language.Caverphone1Test::testCaverphoneRevisitedCommonCodeAT1111" ]
private static final String SIX_1 = "111111";
@Test public void testCaverphoneRevisitedCommonCodeAT1111() throws EncoderException
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 Caverphone1. * * @version $Id: CaverphoneTest.java 1075947 2011-03-01 17:56:14Z ggregory $ * @since 1.5 */ public class Caverphone1Test extends StringEncoderAbstractTest<Caverphone1> { @Override protected Caverphone1 createStringEncoder() { return new Caverphone1(); } /** * Tests example adapted from version 2.0 http://caversham.otago.ac.nz/files/working/ctp150804.pdf * * AT1111 words: add, aid, at, art, eat, earth, head, hit, hot, hold, hard, heart, it, out, old * * @throws EncoderException */ @Test public void testCaverphoneRevisitedCommonCodeAT1111() throws EncoderException { this.checkEncodingVariations("AT1111", new String[]{ "add", "aid", "at", "art", "eat", "earth", "head", "hit", "hot", "hold", "hard", "heart", "it", "out", "old"}); } @Test public void testEndMb() throws EncoderException { final String[][] data = {{"mb", "M11111"}, {"mbmb", "MPM111"}}; this.checkEncodings(data); } /** * Tests some examples from version 2.0 http://caversham.otago.ac.nz/files/working/ctp150804.pdf * * @throws EncoderException */ @Test public void testIsCaverphoneEquals() throws EncoderException { final Caverphone1 caverphone = new Caverphone1(); Assert.assertFalse("Caverphone encodings should not be equal", caverphone.isEncodeEqual("Peter", "Stevenson")); Assert.assertTrue("Caverphone encodings should be equal", caverphone.isEncodeEqual("Peter", "Peady")); } /** * Tests example from http://caversham.otago.ac.nz/files/working/ctp060902.pdf * * @throws EncoderException */ @Test public void testSpecificationV1Examples() throws EncoderException { final String[][] data = {{"David", "TFT111"}, {"Whittle", "WTL111"}}; this.checkEncodings(data); } /** * Tests examples from http://en.wikipedia.org/wiki/Caverphone * * @throws EncoderException */ @Test public void testWikipediaExamples() throws EncoderException { final String[][] data = {{"Lee", "L11111"}, {"Thompson", "TMPSN1"}}; this.checkEncodings(data); } }
[ { "be_test_class_file": "org/apache/commons/codec/language/Caverphone1.java", "be_test_class_name": "org.apache.commons.codec.language.Caverphone1", "be_test_function_name": "encode", "be_test_function_signature": "(Ljava/lang/String;)Ljava/lang/String;", "line_numbers": [ "46", "47", "48", "52", "55", "59", "60", "61", "62", "63", "66", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100", "101", "102", "103", "104", "105", "106", "107", "108", "109", "110", "111", "112", "113", "114", "117", "118", "121", "124" ], "method_line_rate": 0.9833333333333333 } ]
public class LoopingIteratorTest extends TestCase
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) { } }
// // 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 `testRemoving1` for the `LoopingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests the remove() 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();
149
testRemoving1
```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 `testRemoving1` for the `LoopingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests the remove() method on a LoopingIterator wrapped ArrayList. * @throws Exception If something unexpected occurs. */
123
// // 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 `testRemoving1` for the `LoopingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests the remove() method on a LoopingIterator wrapped ArrayList. * @throws Exception If something unexpected occurs. */ public void testRemoving1() throws Exception {
/** * Tests the remove() 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 `testRemoving1` for the `LoopingIterator` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests the remove() method on a LoopingIterator wrapped ArrayList. * @throws Exception If something unexpected occurs. */ public void testRemoving1() 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;
b8a0ea8669b47ef25f8ab78f8e5d391c9f953adc0e5820978d5762a9b50fb44e
[ "org.apache.commons.collections4.iterators.LoopingIteratorTest::testRemoving1" ]
private final Collection<? extends E> collection; private Iterator<? extends E> iterator;
public void testRemoving1() 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": "hasNext", "be_test_function_signature": "()Z", "line_numbers": [ "72" ], "method_line_rate": 1 }, { "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.8 }, { "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": "remove", "be_test_function_signature": "()V", "line_numbers": [ "109", "110" ], "method_line_rate": 1 }, { "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 } ]
public class HistogramDatasetTests extends TestCase
public void test1553088() { double[] values = {-1.0, 0.0, -Double.MIN_VALUE, 3.0}; HistogramDataset d = new HistogramDataset(); d.addSeries("S1", values, 2, -1.0, 0.0); assertEquals(-1.0, d.getStartXValue(0, 0), EPSILON); assertEquals(-0.5, d.getEndXValue(0, 0), EPSILON); assertEquals(1.0, d.getYValue(0, 0), EPSILON); assertEquals(-0.5, d.getStartXValue(0, 1), EPSILON); assertEquals(0.0, d.getEndXValue(0, 1), EPSILON); assertEquals(3.0, d.getYValue(0, 1), EPSILON); }
// // Abstract Java Tested Class // package org.jfree.data.statistics; // // import java.io.Serializable; // import java.util.ArrayList; // import java.util.HashMap; // import java.util.List; // import java.util.Map; // import org.jfree.chart.event.DatasetChangeInfo; // import org.jfree.chart.util.ObjectUtilities; // import org.jfree.chart.util.PublicCloneable; // import org.jfree.data.event.DatasetChangeEvent; // import org.jfree.data.xy.AbstractIntervalXYDataset; // import org.jfree.data.xy.IntervalXYDataset; // // // // public class HistogramDataset extends AbstractIntervalXYDataset // implements IntervalXYDataset, Cloneable, PublicCloneable, // Serializable { // private static final long serialVersionUID = -6341668077370231153L; // private List list; // private HistogramType type; // // public HistogramDataset(); // public HistogramType getType(); // public void setType(HistogramType type); // public void addSeries(Comparable key, double[] values, int bins); // public void addSeries(Comparable key, // double[] values, // int bins, // double minimum, // double maximum); // private double getMinimum(double[] values); // private double getMaximum(double[] values); // List getBins(int series); // private int getTotal(int series); // private double getBinWidth(int series); // public int getSeriesCount(); // public Comparable getSeriesKey(int series); // public int getItemCount(int series); // public Number getX(int series, int item); // public Number getY(int series, int item); // public Number getStartX(int series, int item); // public Number getEndX(int series, int item); // public Number getStartY(int series, int item); // public Number getEndY(int series, int item); // public boolean equals(Object obj); // public Object clone() throws CloneNotSupportedException; // } // // // Abstract Java Test Class // package org.jfree.data.statistics.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.statistics.HistogramDataset; // // // // public class HistogramDatasetTests extends TestCase { // private static final double EPSILON = 0.0000000001; // // public static Test suite(); // public HistogramDatasetTests(String name); // public void testBins(); // public void testEquals(); // public void testCloning(); // public void testSerialization(); // public void testGetSeriesKey(); // public void testAddSeries(); // public void testAddSeries2(); // public void testBinBoundaries(); // public void test1553088(); // } // You are a professional Java test case writer, please create a test case named `test1553088` for the `HistogramDataset` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Some checks for bug 1553088. An IndexOutOfBoundsException is thrown * when a data value is *very* close to the upper limit of the last bin. */
tests/org/jfree/data/statistics/junit/HistogramDatasetTests.java
package org.jfree.data.statistics; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jfree.chart.event.DatasetChangeInfo; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.event.DatasetChangeEvent; import org.jfree.data.xy.AbstractIntervalXYDataset; import org.jfree.data.xy.IntervalXYDataset;
public HistogramDataset(); public HistogramType getType(); public void setType(HistogramType type); public void addSeries(Comparable key, double[] values, int bins); public void addSeries(Comparable key, double[] values, int bins, double minimum, double maximum); private double getMinimum(double[] values); private double getMaximum(double[] values); List getBins(int series); private int getTotal(int series); private double getBinWidth(int series); public int getSeriesCount(); public Comparable getSeriesKey(int series); public int getItemCount(int series); public Number getX(int series, int item); public Number getY(int series, int item); public Number getStartX(int series, int item); public Number getEndX(int series, int item); public Number getStartY(int series, int item); public Number getEndY(int series, int item); public boolean equals(Object obj); public Object clone() throws CloneNotSupportedException;
256
test1553088
```java // Abstract Java Tested Class package org.jfree.data.statistics; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jfree.chart.event.DatasetChangeInfo; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.event.DatasetChangeEvent; import org.jfree.data.xy.AbstractIntervalXYDataset; import org.jfree.data.xy.IntervalXYDataset; public class HistogramDataset extends AbstractIntervalXYDataset implements IntervalXYDataset, Cloneable, PublicCloneable, Serializable { private static final long serialVersionUID = -6341668077370231153L; private List list; private HistogramType type; public HistogramDataset(); public HistogramType getType(); public void setType(HistogramType type); public void addSeries(Comparable key, double[] values, int bins); public void addSeries(Comparable key, double[] values, int bins, double minimum, double maximum); private double getMinimum(double[] values); private double getMaximum(double[] values); List getBins(int series); private int getTotal(int series); private double getBinWidth(int series); public int getSeriesCount(); public Comparable getSeriesKey(int series); public int getItemCount(int series); public Number getX(int series, int item); public Number getY(int series, int item); public Number getStartX(int series, int item); public Number getEndX(int series, int item); public Number getStartY(int series, int item); public Number getEndY(int series, int item); public boolean equals(Object obj); public Object clone() throws CloneNotSupportedException; } // Abstract Java Test Class package org.jfree.data.statistics.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.statistics.HistogramDataset; public class HistogramDatasetTests extends TestCase { private static final double EPSILON = 0.0000000001; public static Test suite(); public HistogramDatasetTests(String name); public void testBins(); public void testEquals(); public void testCloning(); public void testSerialization(); public void testGetSeriesKey(); public void testAddSeries(); public void testAddSeries2(); public void testBinBoundaries(); public void test1553088(); } ``` You are a professional Java test case writer, please create a test case named `test1553088` for the `HistogramDataset` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Some checks for bug 1553088. An IndexOutOfBoundsException is thrown * when a data value is *very* close to the upper limit of the last bin. */
245
// // Abstract Java Tested Class // package org.jfree.data.statistics; // // import java.io.Serializable; // import java.util.ArrayList; // import java.util.HashMap; // import java.util.List; // import java.util.Map; // import org.jfree.chart.event.DatasetChangeInfo; // import org.jfree.chart.util.ObjectUtilities; // import org.jfree.chart.util.PublicCloneable; // import org.jfree.data.event.DatasetChangeEvent; // import org.jfree.data.xy.AbstractIntervalXYDataset; // import org.jfree.data.xy.IntervalXYDataset; // // // // public class HistogramDataset extends AbstractIntervalXYDataset // implements IntervalXYDataset, Cloneable, PublicCloneable, // Serializable { // private static final long serialVersionUID = -6341668077370231153L; // private List list; // private HistogramType type; // // public HistogramDataset(); // public HistogramType getType(); // public void setType(HistogramType type); // public void addSeries(Comparable key, double[] values, int bins); // public void addSeries(Comparable key, // double[] values, // int bins, // double minimum, // double maximum); // private double getMinimum(double[] values); // private double getMaximum(double[] values); // List getBins(int series); // private int getTotal(int series); // private double getBinWidth(int series); // public int getSeriesCount(); // public Comparable getSeriesKey(int series); // public int getItemCount(int series); // public Number getX(int series, int item); // public Number getY(int series, int item); // public Number getStartX(int series, int item); // public Number getEndX(int series, int item); // public Number getStartY(int series, int item); // public Number getEndY(int series, int item); // public boolean equals(Object obj); // public Object clone() throws CloneNotSupportedException; // } // // // Abstract Java Test Class // package org.jfree.data.statistics.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.statistics.HistogramDataset; // // // // public class HistogramDatasetTests extends TestCase { // private static final double EPSILON = 0.0000000001; // // public static Test suite(); // public HistogramDatasetTests(String name); // public void testBins(); // public void testEquals(); // public void testCloning(); // public void testSerialization(); // public void testGetSeriesKey(); // public void testAddSeries(); // public void testAddSeries2(); // public void testBinBoundaries(); // public void test1553088(); // } // You are a professional Java test case writer, please create a test case named `test1553088` for the `HistogramDataset` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Some checks for bug 1553088. An IndexOutOfBoundsException is thrown * when a data value is *very* close to the upper limit of the last bin. */ public void test1553088() {
/** * Some checks for bug 1553088. An IndexOutOfBoundsException is thrown * when a data value is *very* close to the upper limit of the last bin. */
1
org.jfree.data.statistics.HistogramDataset
tests
```java // Abstract Java Tested Class package org.jfree.data.statistics; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jfree.chart.event.DatasetChangeInfo; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.data.event.DatasetChangeEvent; import org.jfree.data.xy.AbstractIntervalXYDataset; import org.jfree.data.xy.IntervalXYDataset; public class HistogramDataset extends AbstractIntervalXYDataset implements IntervalXYDataset, Cloneable, PublicCloneable, Serializable { private static final long serialVersionUID = -6341668077370231153L; private List list; private HistogramType type; public HistogramDataset(); public HistogramType getType(); public void setType(HistogramType type); public void addSeries(Comparable key, double[] values, int bins); public void addSeries(Comparable key, double[] values, int bins, double minimum, double maximum); private double getMinimum(double[] values); private double getMaximum(double[] values); List getBins(int series); private int getTotal(int series); private double getBinWidth(int series); public int getSeriesCount(); public Comparable getSeriesKey(int series); public int getItemCount(int series); public Number getX(int series, int item); public Number getY(int series, int item); public Number getStartX(int series, int item); public Number getEndX(int series, int item); public Number getStartY(int series, int item); public Number getEndY(int series, int item); public boolean equals(Object obj); public Object clone() throws CloneNotSupportedException; } // Abstract Java Test Class package org.jfree.data.statistics.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.statistics.HistogramDataset; public class HistogramDatasetTests extends TestCase { private static final double EPSILON = 0.0000000001; public static Test suite(); public HistogramDatasetTests(String name); public void testBins(); public void testEquals(); public void testCloning(); public void testSerialization(); public void testGetSeriesKey(); public void testAddSeries(); public void testAddSeries2(); public void testBinBoundaries(); public void test1553088(); } ``` You are a professional Java test case writer, please create a test case named `test1553088` for the `HistogramDataset` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Some checks for bug 1553088. An IndexOutOfBoundsException is thrown * when a data value is *very* close to the upper limit of the last bin. */ public void test1553088() { ```
public class HistogramDataset extends AbstractIntervalXYDataset implements IntervalXYDataset, Cloneable, PublicCloneable, Serializable
package org.jfree.data.statistics.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.statistics.HistogramDataset;
public static Test suite(); public HistogramDatasetTests(String name); public void testBins(); public void testEquals(); public void testCloning(); public void testSerialization(); public void testGetSeriesKey(); public void testAddSeries(); public void testAddSeries2(); public void testBinBoundaries(); public void test1553088();
ba919fcfe9d145d7e7d2696c6b50379cd0446b3aaf3201bc16dce62785ddd6ac
[ "org.jfree.data.statistics.junit.HistogramDatasetTests::test1553088" ]
private static final long serialVersionUID = -6341668077370231153L; private List list; private HistogramType type;
public void test1553088()
private static final double EPSILON = 0.0000000001;
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.] * * -------------------------- * HistogramDatasetTests.java * -------------------------- * (C) Copyright 2004-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 01-Mar-2004 : Version 1 (DG); * 08-Jun-2005 : Added test for getSeriesKey(int) bug (DG); * 03-Aug-2006 : Added testAddSeries() and testBinBoundaries() method (DG); * 22-May-2008 : Added testAddSeries2() and enhanced testCloning() (DG); * */ package org.jfree.data.statistics.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.statistics.HistogramDataset; /** * Tests for the {@link HistogramDataset} class. */ public class HistogramDatasetTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(HistogramDatasetTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public HistogramDatasetTests(String name) { super(name); } private static final double EPSILON = 0.0000000001; /** * Some checks that the correct values are assigned to bins. */ public void testBins() { double[] values = {1.0, 2.0, 3.0, 4.0, 6.0, 12.0, 5.0, 6.3, 4.5}; HistogramDataset hd = new HistogramDataset(); hd.addSeries("Series 1", values, 5); assertEquals(hd.getYValue(0, 0), 3.0, EPSILON); assertEquals(hd.getYValue(0, 1), 3.0, EPSILON); assertEquals(hd.getYValue(0, 2), 2.0, EPSILON); assertEquals(hd.getYValue(0, 3), 0.0, EPSILON); assertEquals(hd.getYValue(0, 4), 1.0, EPSILON); } /** * Confirm that the equals method can distinguish all the required fields. */ public void testEquals() { double[] values = {1.0, 2.0, 3.0, 4.0, 6.0, 12.0, 5.0, 6.3, 4.5}; HistogramDataset d1 = new HistogramDataset(); d1.addSeries("Series 1", values, 5); HistogramDataset d2 = new HistogramDataset(); d2.addSeries("Series 1", values, 5); assertTrue(d1.equals(d2)); assertTrue(d2.equals(d1)); d1.addSeries("Series 2", new double[] {1.0, 2.0, 3.0}, 2); assertFalse(d1.equals(d2)); d2.addSeries("Series 2", new double[] {1.0, 2.0, 3.0}, 2); assertTrue(d1.equals(d2)); } /** * Confirm that cloning works. */ public void testCloning() { double[] values = {1.0, 2.0, 3.0, 4.0, 6.0, 12.0, 5.0, 6.3, 4.5}; HistogramDataset d1 = new HistogramDataset(); d1.addSeries("Series 1", values, 5); HistogramDataset d2 = null; try { d2 = (HistogramDataset) d1.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } assertTrue(d1 != d2); assertTrue(d1.getClass() == d2.getClass()); assertTrue(d1.equals(d2)); // simple check for independence d1.addSeries("Series 2", new double[] {1.0, 2.0, 3.0}, 2); assertFalse(d1.equals(d2)); d2.addSeries("Series 2", new double[] {1.0, 2.0, 3.0}, 2); assertTrue(d1.equals(d2)); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { double[] values = {1.0, 2.0, 3.0, 4.0, 6.0, 12.0, 5.0, 6.3, 4.5}; HistogramDataset d1 = new HistogramDataset(); d1.addSeries("Series 1", values, 5); HistogramDataset d2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(d1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); d2 = (HistogramDataset) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(d1, d2); // simple check for independence d1.addSeries("Series 2", new double[] {1.0, 2.0, 3.0}, 2); assertFalse(d1.equals(d2)); d2.addSeries("Series 2", new double[] {1.0, 2.0, 3.0}, 2); assertTrue(d1.equals(d2)); } /** * A test for a bug reported in the forum where the series name isn't being * returned correctly. */ public void testGetSeriesKey() { double[] values = {1.0, 2.0, 3.0, 4.0, 6.0, 12.0, 5.0, 6.3, 4.5}; HistogramDataset d1 = new HistogramDataset(); d1.addSeries("Series 1", values, 5); assertEquals("Series 1", d1.getSeriesKey(0)); } /** * Some checks for the addSeries() method. */ public void testAddSeries() { double[] values = {-1.0, 0.0, 0.1, 0.9, 1.0, 1.1, 1.9, 2.0, 3.0}; HistogramDataset d = new HistogramDataset(); d.addSeries("S1", values, 2, 0.0, 2.0); assertEquals(0.0, d.getStartXValue(0, 0), EPSILON); assertEquals(1.0, d.getEndXValue(0, 0), EPSILON); assertEquals(4.0, d.getYValue(0, 0), EPSILON); assertEquals(1.0, d.getStartXValue(0, 1), EPSILON); assertEquals(2.0, d.getEndXValue(0, 1), EPSILON); assertEquals(5.0, d.getYValue(0, 1), EPSILON); } /** * Another check for the addSeries() method. */ public void testAddSeries2() { double[] values = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0}; HistogramDataset hd = new HistogramDataset(); hd.addSeries("S1", values, 5); assertEquals(0.0, hd.getStartXValue(0, 0), EPSILON); assertEquals(1.0, hd.getEndXValue(0, 0), EPSILON); assertEquals(1.0, hd.getYValue(0, 0), EPSILON); assertEquals(1.0, hd.getStartXValue(0, 1), EPSILON); assertEquals(2.0, hd.getEndXValue(0, 1), EPSILON); assertEquals(1.0, hd.getYValue(0, 1), EPSILON); assertEquals(2.0, hd.getStartXValue(0, 2), EPSILON); assertEquals(3.0, hd.getEndXValue(0, 2), EPSILON); assertEquals(1.0, hd.getYValue(0, 2), EPSILON); assertEquals(3.0, hd.getStartXValue(0, 3), EPSILON); assertEquals(4.0, hd.getEndXValue(0, 3), EPSILON); assertEquals(1.0, hd.getYValue(0, 3), EPSILON); assertEquals(4.0, hd.getStartXValue(0, 4), EPSILON); assertEquals(5.0, hd.getEndXValue(0, 4), EPSILON); assertEquals(2.0, hd.getYValue(0, 4), EPSILON); } /** * This test is derived from a reported bug. */ public void testBinBoundaries() { double[] values = {-5.000000000000286E-5}; int bins = 1260; double minimum = -0.06307522528160199; double maximum = 0.06297522528160199; HistogramDataset d = new HistogramDataset(); d.addSeries("S1", values, bins, minimum, maximum); assertEquals(0.0, d.getYValue(0, 629), EPSILON); assertEquals(1.0, d.getYValue(0, 630), EPSILON); assertEquals(0.0, d.getYValue(0, 631), EPSILON); assertTrue(values[0] > d.getStartXValue(0, 630)); assertTrue(values[0] < d.getEndXValue(0, 630)); } /** * Some checks for bug 1553088. An IndexOutOfBoundsException is thrown * when a data value is *very* close to the upper limit of the last bin. */ public void test1553088() { double[] values = {-1.0, 0.0, -Double.MIN_VALUE, 3.0}; HistogramDataset d = new HistogramDataset(); d.addSeries("S1", values, 2, -1.0, 0.0); assertEquals(-1.0, d.getStartXValue(0, 0), EPSILON); assertEquals(-0.5, d.getEndXValue(0, 0), EPSILON); assertEquals(1.0, d.getYValue(0, 0), EPSILON); assertEquals(-0.5, d.getStartXValue(0, 1), EPSILON); assertEquals(0.0, d.getEndXValue(0, 1), EPSILON); assertEquals(3.0, d.getYValue(0, 1), EPSILON); } }
[ { "be_test_class_file": "org/jfree/data/statistics/HistogramDataset.java", "be_test_class_name": "org.jfree.data.statistics.HistogramDataset", "be_test_function_name": "addSeries", "be_test_function_signature": "(Ljava/lang/Comparable;[DIDD)V", "line_numbers": [ "158", "159", "161", "162", "164", "165", "168", "170", "172", "173", "178", "179", "182", "183", "184", "186", "189", "190", "191", "192", "193", "194", "196", "200", "201", "204", "205", "208", "209", "210", "211", "212", "213", "214" ], "method_line_rate": 0.8823529411764706 }, { "be_test_class_file": "org/jfree/data/statistics/HistogramDataset.java", "be_test_class_name": "org.jfree.data.statistics.HistogramDataset", "be_test_function_name": "getBinWidth", "be_test_function_signature": "(I)D", "line_numbers": [ "296", "297" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/statistics/HistogramDataset.java", "be_test_class_name": "org.jfree.data.statistics.HistogramDataset", "be_test_function_name": "getBins", "be_test_function_signature": "(I)Ljava/util/List;", "line_numbers": [ "272", "273" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/statistics/HistogramDataset.java", "be_test_class_name": "org.jfree.data.statistics.HistogramDataset", "be_test_function_name": "getEndX", "be_test_function_signature": "(II)Ljava/lang/Number;", "line_numbers": [ "426", "427", "428" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/statistics/HistogramDataset.java", "be_test_class_name": "org.jfree.data.statistics.HistogramDataset", "be_test_function_name": "getStartX", "be_test_function_signature": "(II)Ljava/lang/Number;", "line_numbers": [ "408", "409", "410" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/statistics/HistogramDataset.java", "be_test_class_name": "org.jfree.data.statistics.HistogramDataset", "be_test_function_name": "getTotal", "be_test_function_signature": "(I)I", "line_numbers": [ "284", "285" ], "method_line_rate": 1 }, { "be_test_class_file": "org/jfree/data/statistics/HistogramDataset.java", "be_test_class_name": "org.jfree.data.statistics.HistogramDataset", "be_test_function_name": "getY", "be_test_function_signature": "(II)Ljava/lang/Number;", "line_numbers": [ "376", "377", "378", "379", "381", "382", "384", "385", "387", "388", "391" ], "method_line_rate": 0.5454545454545454 } ]
public class CovarianceTest
@Test public void testConsistency() { final RealMatrix matrix = createRealMatrix(swissData, 47, 5); final RealMatrix covarianceMatrix = new Covariance(matrix).getCovarianceMatrix(); // Variances on the diagonal Variance variance = new Variance(); for (int i = 0; i < 5; i++) { Assert.assertEquals(variance.evaluate(matrix.getColumn(i)), covarianceMatrix.getEntry(i,i), 10E-14); } // Symmetry, column-consistency Assert.assertEquals(covarianceMatrix.getEntry(2, 3), new Covariance().covariance(matrix.getColumn(2), matrix.getColumn(3), true), 10E-14); Assert.assertEquals(covarianceMatrix.getEntry(2, 3), covarianceMatrix.getEntry(3, 2), Double.MIN_VALUE); // All columns same -> all entries = column variance RealMatrix repeatedColumns = new Array2DRowRealMatrix(47, 3); for (int i = 0; i < 3; i++) { repeatedColumns.setColumnMatrix(i, matrix.getColumnMatrix(0)); } RealMatrix repeatedCovarianceMatrix = new Covariance(repeatedColumns).getCovarianceMatrix(); double columnVariance = variance.evaluate(matrix.getColumn(0)); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Assert.assertEquals(columnVariance, repeatedCovarianceMatrix.getEntry(i, j), 10E-14); } } // Check bias-correction defaults double[][] data = matrix.getData(); TestUtils.assertEquals("Covariances", covarianceMatrix, new Covariance().computeCovarianceMatrix(data),Double.MIN_VALUE); TestUtils.assertEquals("Covariances", covarianceMatrix, new Covariance().computeCovarianceMatrix(data, true),Double.MIN_VALUE); double[] x = data[0]; double[] y = data[1]; Assert.assertEquals(new Covariance().covariance(x, y), new Covariance().covariance(x, y, true), Double.MIN_VALUE); }
// 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 // }; // protected final double[] swissData = 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 // }; // // @Test // public void testLongly(); // @Test // public void testSwissFertility(); // @Test // public void testConstant(); // @Test // public void testOneColumn(); // @Test // public void testInsufficientData(); // @Test // public void testConsistency(); // protected RealMatrix createRealMatrix(double[] data, int nRows, int nCols); // } // You are a professional Java test case writer, please create a test case named `testConsistency` for the `Covariance` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Verify that diagonal entries are consistent with Variance computation and matrix matches * column-by-column covariances */
src/test/java/org/apache/commons/math3/stat/correlation/CovarianceTest.java
package org.apache.commons.math3.stat.correlation; import org.apache.commons.math3.exception.MathIllegalArgumentException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.BlockRealMatrix; import org.apache.commons.math3.stat.descriptive.moment.Mean; import org.apache.commons.math3.stat.descriptive.moment.Variance;
public Covariance(); public Covariance(double[][] data, boolean biasCorrected) throws MathIllegalArgumentException, NotStrictlyPositiveException; public Covariance(double[][] data) throws MathIllegalArgumentException, NotStrictlyPositiveException; public Covariance(RealMatrix matrix, boolean biasCorrected) throws MathIllegalArgumentException; public Covariance(RealMatrix matrix) throws MathIllegalArgumentException; public RealMatrix getCovarianceMatrix(); public int getN(); protected RealMatrix computeCovarianceMatrix(RealMatrix matrix, boolean biasCorrected) throws MathIllegalArgumentException; protected RealMatrix computeCovarianceMatrix(RealMatrix matrix) throws MathIllegalArgumentException; protected RealMatrix computeCovarianceMatrix(double[][] data, boolean biasCorrected) throws MathIllegalArgumentException, NotStrictlyPositiveException; protected RealMatrix computeCovarianceMatrix(double[][] data) throws MathIllegalArgumentException, NotStrictlyPositiveException; public double covariance(final double[] xArray, final double[] yArray, boolean biasCorrected) throws MathIllegalArgumentException; public double covariance(final double[] xArray, final double[] yArray) throws MathIllegalArgumentException; private void checkSufficientData(final RealMatrix matrix) throws MathIllegalArgumentException;
240
testConsistency
```java 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 }; protected final double[] swissData = 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 }; @Test public void testLongly(); @Test public void testSwissFertility(); @Test public void testConstant(); @Test public void testOneColumn(); @Test public void testInsufficientData(); @Test public void testConsistency(); protected RealMatrix createRealMatrix(double[] data, int nRows, int nCols); } ``` You are a professional Java test case writer, please create a test case named `testConsistency` for the `Covariance` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Verify that diagonal entries are consistent with Variance computation and matrix matches * column-by-column covariances */
200
// 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 // }; // protected final double[] swissData = 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 // }; // // @Test // public void testLongly(); // @Test // public void testSwissFertility(); // @Test // public void testConstant(); // @Test // public void testOneColumn(); // @Test // public void testInsufficientData(); // @Test // public void testConsistency(); // protected RealMatrix createRealMatrix(double[] data, int nRows, int nCols); // } // You are a professional Java test case writer, please create a test case named `testConsistency` for the `Covariance` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Verify that diagonal entries are consistent with Variance computation and matrix matches * column-by-column covariances */ @Test public void testConsistency() {
/** * Verify that diagonal entries are consistent with Variance computation and matrix matches * column-by-column covariances */
1
org.apache.commons.math3.stat.correlation.Covariance
src/test/java
```java 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 }; protected final double[] swissData = 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 }; @Test public void testLongly(); @Test public void testSwissFertility(); @Test public void testConstant(); @Test public void testOneColumn(); @Test public void testInsufficientData(); @Test public void testConsistency(); protected RealMatrix createRealMatrix(double[] data, int nRows, int nCols); } ``` You are a professional Java test case writer, please create a test case named `testConsistency` for the `Covariance` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Verify that diagonal entries are consistent with Variance computation and matrix matches * column-by-column covariances */ @Test public void testConsistency() { ```
public class Covariance
package org.apache.commons.math3.stat.correlation; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.stat.descriptive.moment.Variance; import org.junit.Assert; import org.junit.Test;
@Test public void testLongly(); @Test public void testSwissFertility(); @Test public void testConstant(); @Test public void testOneColumn(); @Test public void testInsufficientData(); @Test public void testConsistency(); protected RealMatrix createRealMatrix(double[] data, int nRows, int nCols);
baebc8b8875f0038dcb88a2ec2f63734578c2ed1c2aff1c0d424c44c581b8ece
[ "org.apache.commons.math3.stat.correlation.CovarianceTest::testConsistency" ]
private final RealMatrix covarianceMatrix; private final int n;
@Test public void testConsistency()
protected final double[] longleyData = 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 }; protected final double[] swissData = 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 };
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.correlation; import org.apache.commons.math3.TestUtils; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.stat.descriptive.moment.Variance; import org.junit.Assert; import org.junit.Test; public class CovarianceTest { protected final double[] longleyData = 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 }; protected final double[] swissData = 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 }; /** * Test Longley dataset against R. * 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. * * Data are from NIST: * http://www.itl.nist.gov/div898/strd/lls/data/LINKS/DATA/Longley.dat */ @Test public void testLongly() { RealMatrix matrix = createRealMatrix(longleyData, 16, 7); RealMatrix covarianceMatrix = new Covariance(matrix).getCovarianceMatrix(); double[] rData = new double[] { 12333921.73333333246, 3.679666000000000e+04, 343330206.333333313, 1649102.666666666744, 1117681.066666666651, 23461965.733333334, 16240.93333333333248, 36796.66000000000, 1.164576250000000e+02, 1063604.115416667, 6258.666250000000, 3490.253750000000, 73503.000000000, 50.92333333333334, 343330206.33333331347, 1.063604115416667e+06, 9879353659.329166412, 56124369.854166664183, 30880428.345833335072, 685240944.600000024, 470977.90000000002328, 1649102.66666666674, 6.258666250000000e+03, 56124369.854166664, 873223.429166666698, -115378.762499999997, 4462741.533333333, 2973.03333333333330, 1117681.06666666665, 3.490253750000000e+03, 30880428.345833335, -115378.762499999997, 484304.095833333326, 1764098.133333333, 1382.43333333333339, 23461965.73333333433, 7.350300000000000e+04, 685240944.600000024, 4462741.533333333209, 1764098.133333333302, 48387348.933333330, 32917.40000000000146, 16240.93333333333, 5.092333333333334e+01, 470977.900000000, 2973.033333333333, 1382.433333333333, 32917.40000000, 22.66666666666667 }; TestUtils.assertEquals("covariance matrix", createRealMatrix(rData, 7, 7), covarianceMatrix, 10E-9); } /** * Test R Swiss fertility dataset against R. * Data Source: R datasets package */ @Test public void testSwissFertility() { RealMatrix matrix = createRealMatrix(swissData, 47, 5); RealMatrix covarianceMatrix = new Covariance(matrix).getCovarianceMatrix(); double[] rData = new double[] { 156.0424976873265, 100.1691489361702, -64.36692876965772, -79.7295097132285, 241.5632030527289, 100.169148936170251, 515.7994172062905, -124.39283071230344, -139.6574005550416, 379.9043755781684, -64.3669287696577, -124.3928307123034, 63.64662349676226, 53.5758556891767, -190.5606105457909, -79.7295097132285, -139.6574005550416, 53.57585568917669, 92.4560592044403, -61.6988297872340, 241.5632030527289, 379.9043755781684, -190.56061054579092, -61.6988297872340, 1739.2945371877890 }; TestUtils.assertEquals("covariance matrix", createRealMatrix(rData, 5, 5), covarianceMatrix, 10E-13); } /** * Constant column */ @Test public void testConstant() { double[] noVariance = new double[] {1, 1, 1, 1}; double[] values = new double[] {1, 2, 3, 4}; Assert.assertEquals(0d, new Covariance().covariance(noVariance, values, true), Double.MIN_VALUE); Assert.assertEquals(0d, new Covariance().covariance(noVariance, noVariance, true), Double.MIN_VALUE); } /** * One column */ @Test public void testOneColumn() { RealMatrix cov = new Covariance(new double[][] {{1}, {2}}, false).getCovarianceMatrix(); Assert.assertEquals(1, cov.getRowDimension()); Assert.assertEquals(1, cov.getColumnDimension()); Assert.assertEquals(0.25, cov.getEntry(0, 0), 1.0e-15); } /** * Insufficient data */ @Test public void testInsufficientData() { double[] one = new double[] {1}; double[] two = new double[] {2}; try { new Covariance().covariance(one, two, false); Assert.fail("Expecting IllegalArgumentException"); } catch (IllegalArgumentException ex) { // Expected } try { new Covariance(new double[][] {{},{}}); Assert.fail("Expecting NotStrictlyPositiveException"); } catch (NotStrictlyPositiveException ex) { // Expected } } /** * Verify that diagonal entries are consistent with Variance computation and matrix matches * column-by-column covariances */ @Test public void testConsistency() { final RealMatrix matrix = createRealMatrix(swissData, 47, 5); final RealMatrix covarianceMatrix = new Covariance(matrix).getCovarianceMatrix(); // Variances on the diagonal Variance variance = new Variance(); for (int i = 0; i < 5; i++) { Assert.assertEquals(variance.evaluate(matrix.getColumn(i)), covarianceMatrix.getEntry(i,i), 10E-14); } // Symmetry, column-consistency Assert.assertEquals(covarianceMatrix.getEntry(2, 3), new Covariance().covariance(matrix.getColumn(2), matrix.getColumn(3), true), 10E-14); Assert.assertEquals(covarianceMatrix.getEntry(2, 3), covarianceMatrix.getEntry(3, 2), Double.MIN_VALUE); // All columns same -> all entries = column variance RealMatrix repeatedColumns = new Array2DRowRealMatrix(47, 3); for (int i = 0; i < 3; i++) { repeatedColumns.setColumnMatrix(i, matrix.getColumnMatrix(0)); } RealMatrix repeatedCovarianceMatrix = new Covariance(repeatedColumns).getCovarianceMatrix(); double columnVariance = variance.evaluate(matrix.getColumn(0)); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Assert.assertEquals(columnVariance, repeatedCovarianceMatrix.getEntry(i, j), 10E-14); } } // Check bias-correction defaults double[][] data = matrix.getData(); TestUtils.assertEquals("Covariances", covarianceMatrix, new Covariance().computeCovarianceMatrix(data),Double.MIN_VALUE); TestUtils.assertEquals("Covariances", covarianceMatrix, new Covariance().computeCovarianceMatrix(data, true),Double.MIN_VALUE); double[] x = data[0]; double[] y = data[1]; Assert.assertEquals(new Covariance().covariance(x, y), new Covariance().covariance(x, y, true), Double.MIN_VALUE); } protected RealMatrix createRealMatrix(double[] data, int nRows, int nCols) { double[][] matrixData = new double[nRows][nCols]; int ptr = 0; for (int i = 0; i < nRows; i++) { System.arraycopy(data, ptr, matrixData[i], 0, nCols); ptr += nCols; } return new Array2DRowRealMatrix(matrixData); } }
[ { "be_test_class_file": "org/apache/commons/math3/stat/correlation/Covariance.java", "be_test_class_name": "org.apache.commons.math3.stat.correlation.Covariance", "be_test_function_name": "checkSufficientData", "be_test_function_signature": "(Lorg/apache/commons/math3/linear/RealMatrix;)V", "line_numbers": [ "288", "289", "290", "291", "295" ], "method_line_rate": 0.8 }, { "be_test_class_file": "org/apache/commons/math3/stat/correlation/Covariance.java", "be_test_class_name": "org.apache.commons.math3.stat.correlation.Covariance", "be_test_function_name": "computeCovarianceMatrix", "be_test_function_signature": "(Lorg/apache/commons/math3/linear/RealMatrix;Z)Lorg/apache/commons/math3/linear/RealMatrix;", "line_numbers": [ "170", "171", "172", "173", "174", "175", "176", "177", "179", "181" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/stat/correlation/Covariance.java", "be_test_class_name": "org.apache.commons.math3.stat.correlation.Covariance", "be_test_function_name": "computeCovarianceMatrix", "be_test_function_signature": "([[D)Lorg/apache/commons/math3/linear/RealMatrix;", "line_numbers": [ "225" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/stat/correlation/Covariance.java", "be_test_class_name": "org.apache.commons.math3.stat.correlation.Covariance", "be_test_function_name": "computeCovarianceMatrix", "be_test_function_signature": "([[DZ)Lorg/apache/commons/math3/linear/RealMatrix;", "line_numbers": [ "210" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/stat/correlation/Covariance.java", "be_test_class_name": "org.apache.commons.math3.stat.correlation.Covariance", "be_test_function_name": "covariance", "be_test_function_signature": "([D[D)D", "line_numbers": [ "277" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/stat/correlation/Covariance.java", "be_test_class_name": "org.apache.commons.math3.stat.correlation.Covariance", "be_test_function_name": "covariance", "be_test_function_signature": "([D[DZ)D", "line_numbers": [ "242", "243", "244", "245", "246", "248", "249", "252", "253", "254", "255", "256", "257", "260" ], "method_line_rate": 0.8571428571428571 }, { "be_test_class_file": "org/apache/commons/math3/stat/correlation/Covariance.java", "be_test_class_name": "org.apache.commons.math3.stat.correlation.Covariance", "be_test_function_name": "getCovarianceMatrix", "be_test_function_signature": "()Lorg/apache/commons/math3/linear/RealMatrix;", "line_numbers": [ "148" ], "method_line_rate": 1 } ]
public class BaseRuleFactoryTest
@Test public void testConcurrentCreation() throws InterruptedException, ExecutionException { // Number of times the same rule will be called. final int numTasks = 20; final ThreadPoolExecutor exec = new ThreadPoolExecutor(3, numTasks, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2)); final List<Future<Pair<double[], double[]>>> results = new ArrayList<Future<Pair<double[], double[]>>>(); for (int i = 0; i < numTasks; i++) { results.add(exec.submit(new RuleBuilder())); } // Ensure that all computations have completed. for (Future<Pair<double[], double[]>> f : results) { f.get(); } // Assertion would fail if "getRuleInternal" were not "synchronized". final int n = RuleBuilder.getNumberOfCalls(); Assert.assertEquals("Rule computation was called " + n + " times", 1, n); }
// // Abstract Java Tested Class // package org.apache.commons.math3.analysis.integration.gauss; // // import java.util.Map; // import java.util.TreeMap; // import org.apache.commons.math3.util.Pair; // import org.apache.commons.math3.exception.DimensionMismatchException; // import org.apache.commons.math3.exception.NotStrictlyPositiveException; // import org.apache.commons.math3.exception.util.LocalizedFormats; // // // // public abstract class BaseRuleFactory<T extends Number> { // private final Map<Integer, Pair<T[], T[]>> pointsAndWeights // = new TreeMap<Integer, Pair<T[], T[]>>(); // private final Map<Integer, Pair<double[], double[]>> pointsAndWeightsDouble // = new TreeMap<Integer, Pair<double[], double[]>>(); // // public Pair<double[], double[]> getRule(int numberOfPoints) // throws NotStrictlyPositiveException, DimensionMismatchException; // protected synchronized Pair<T[], T[]> getRuleInternal(int numberOfPoints) // throws DimensionMismatchException; // protected void addRule(Pair<T[], T[]> rule) throws DimensionMismatchException; // protected abstract Pair<T[], T[]> computeRule(int numberOfPoints) // throws DimensionMismatchException; // private static <T extends Number> Pair<double[], double[]> convertToDouble(Pair<T[], T[]> rule); // } // // // Abstract Java Test Class // package org.apache.commons.math3.analysis.integration.gauss; // // import java.util.List; // import java.util.ArrayList; // import java.util.concurrent.ThreadPoolExecutor; // import java.util.concurrent.ArrayBlockingQueue; // import java.util.concurrent.TimeUnit; // import java.util.concurrent.Callable; // import java.util.concurrent.Future; // import java.util.concurrent.ExecutionException; // import java.util.concurrent.atomic.AtomicInteger; // import org.apache.commons.math3.util.Pair; // import org.junit.Test; // import org.junit.Assert; // // // // public class BaseRuleFactoryTest { // private static final DummyRuleFactory factory = new DummyRuleFactory(); // private static AtomicInteger nCalls = new AtomicInteger(); // // @Test // public void testConcurrentCreation() throws InterruptedException, // ExecutionException; // public Pair<double[], double[]> call(); // public static int getNumberOfCalls(); // @Override // protected Pair<Double[], Double[]> computeRule(int order); // public int getNumberOfCalls(); // } // You are a professional Java test case writer, please create a test case named `testConcurrentCreation` for the `BaseRuleFactory` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests that a given rule rule will be computed and added once to the cache * whatever the number of times this rule is called concurrently. */
src/test/java/org/apache/commons/math3/analysis/integration/gauss/BaseRuleFactoryTest.java
package org.apache.commons.math3.analysis.integration.gauss; import java.util.Map; import java.util.TreeMap; import org.apache.commons.math3.util.Pair; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.util.LocalizedFormats;
public Pair<double[], double[]> getRule(int numberOfPoints) throws NotStrictlyPositiveException, DimensionMismatchException; protected synchronized Pair<T[], T[]> getRuleInternal(int numberOfPoints) throws DimensionMismatchException; protected void addRule(Pair<T[], T[]> rule) throws DimensionMismatchException; protected abstract Pair<T[], T[]> computeRule(int numberOfPoints) throws DimensionMismatchException; private static <T extends Number> Pair<double[], double[]> convertToDouble(Pair<T[], T[]> rule);
65
testConcurrentCreation
```java // Abstract Java Tested Class package org.apache.commons.math3.analysis.integration.gauss; import java.util.Map; import java.util.TreeMap; import org.apache.commons.math3.util.Pair; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.util.LocalizedFormats; public abstract class BaseRuleFactory<T extends Number> { private final Map<Integer, Pair<T[], T[]>> pointsAndWeights = new TreeMap<Integer, Pair<T[], T[]>>(); private final Map<Integer, Pair<double[], double[]>> pointsAndWeightsDouble = new TreeMap<Integer, Pair<double[], double[]>>(); public Pair<double[], double[]> getRule(int numberOfPoints) throws NotStrictlyPositiveException, DimensionMismatchException; protected synchronized Pair<T[], T[]> getRuleInternal(int numberOfPoints) throws DimensionMismatchException; protected void addRule(Pair<T[], T[]> rule) throws DimensionMismatchException; protected abstract Pair<T[], T[]> computeRule(int numberOfPoints) throws DimensionMismatchException; private static <T extends Number> Pair<double[], double[]> convertToDouble(Pair<T[], T[]> rule); } // Abstract Java Test Class package org.apache.commons.math3.analysis.integration.gauss; import java.util.List; import java.util.ArrayList; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.math3.util.Pair; import org.junit.Test; import org.junit.Assert; public class BaseRuleFactoryTest { private static final DummyRuleFactory factory = new DummyRuleFactory(); private static AtomicInteger nCalls = new AtomicInteger(); @Test public void testConcurrentCreation() throws InterruptedException, ExecutionException; public Pair<double[], double[]> call(); public static int getNumberOfCalls(); @Override protected Pair<Double[], Double[]> computeRule(int order); public int getNumberOfCalls(); } ``` You are a professional Java test case writer, please create a test case named `testConcurrentCreation` for the `BaseRuleFactory` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests that a given rule rule will be computed and added once to the cache * whatever the number of times this rule is called concurrently. */
41
// // Abstract Java Tested Class // package org.apache.commons.math3.analysis.integration.gauss; // // import java.util.Map; // import java.util.TreeMap; // import org.apache.commons.math3.util.Pair; // import org.apache.commons.math3.exception.DimensionMismatchException; // import org.apache.commons.math3.exception.NotStrictlyPositiveException; // import org.apache.commons.math3.exception.util.LocalizedFormats; // // // // public abstract class BaseRuleFactory<T extends Number> { // private final Map<Integer, Pair<T[], T[]>> pointsAndWeights // = new TreeMap<Integer, Pair<T[], T[]>>(); // private final Map<Integer, Pair<double[], double[]>> pointsAndWeightsDouble // = new TreeMap<Integer, Pair<double[], double[]>>(); // // public Pair<double[], double[]> getRule(int numberOfPoints) // throws NotStrictlyPositiveException, DimensionMismatchException; // protected synchronized Pair<T[], T[]> getRuleInternal(int numberOfPoints) // throws DimensionMismatchException; // protected void addRule(Pair<T[], T[]> rule) throws DimensionMismatchException; // protected abstract Pair<T[], T[]> computeRule(int numberOfPoints) // throws DimensionMismatchException; // private static <T extends Number> Pair<double[], double[]> convertToDouble(Pair<T[], T[]> rule); // } // // // Abstract Java Test Class // package org.apache.commons.math3.analysis.integration.gauss; // // import java.util.List; // import java.util.ArrayList; // import java.util.concurrent.ThreadPoolExecutor; // import java.util.concurrent.ArrayBlockingQueue; // import java.util.concurrent.TimeUnit; // import java.util.concurrent.Callable; // import java.util.concurrent.Future; // import java.util.concurrent.ExecutionException; // import java.util.concurrent.atomic.AtomicInteger; // import org.apache.commons.math3.util.Pair; // import org.junit.Test; // import org.junit.Assert; // // // // public class BaseRuleFactoryTest { // private static final DummyRuleFactory factory = new DummyRuleFactory(); // private static AtomicInteger nCalls = new AtomicInteger(); // // @Test // public void testConcurrentCreation() throws InterruptedException, // ExecutionException; // public Pair<double[], double[]> call(); // public static int getNumberOfCalls(); // @Override // protected Pair<Double[], Double[]> computeRule(int order); // public int getNumberOfCalls(); // } // You are a professional Java test case writer, please create a test case named `testConcurrentCreation` for the `BaseRuleFactory` class, utilizing the provided abstract Java class context information and the following natural language annotations. /** * Tests that a given rule rule will be computed and added once to the cache * whatever the number of times this rule is called concurrently. */ @Test public void testConcurrentCreation() throws InterruptedException, ExecutionException {
/** * Tests that a given rule rule will be computed and added once to the cache * whatever the number of times this rule is called concurrently. */
1
org.apache.commons.math3.analysis.integration.gauss.BaseRuleFactory
src/test/java
```java // Abstract Java Tested Class package org.apache.commons.math3.analysis.integration.gauss; import java.util.Map; import java.util.TreeMap; import org.apache.commons.math3.util.Pair; import org.apache.commons.math3.exception.DimensionMismatchException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.exception.util.LocalizedFormats; public abstract class BaseRuleFactory<T extends Number> { private final Map<Integer, Pair<T[], T[]>> pointsAndWeights = new TreeMap<Integer, Pair<T[], T[]>>(); private final Map<Integer, Pair<double[], double[]>> pointsAndWeightsDouble = new TreeMap<Integer, Pair<double[], double[]>>(); public Pair<double[], double[]> getRule(int numberOfPoints) throws NotStrictlyPositiveException, DimensionMismatchException; protected synchronized Pair<T[], T[]> getRuleInternal(int numberOfPoints) throws DimensionMismatchException; protected void addRule(Pair<T[], T[]> rule) throws DimensionMismatchException; protected abstract Pair<T[], T[]> computeRule(int numberOfPoints) throws DimensionMismatchException; private static <T extends Number> Pair<double[], double[]> convertToDouble(Pair<T[], T[]> rule); } // Abstract Java Test Class package org.apache.commons.math3.analysis.integration.gauss; import java.util.List; import java.util.ArrayList; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.math3.util.Pair; import org.junit.Test; import org.junit.Assert; public class BaseRuleFactoryTest { private static final DummyRuleFactory factory = new DummyRuleFactory(); private static AtomicInteger nCalls = new AtomicInteger(); @Test public void testConcurrentCreation() throws InterruptedException, ExecutionException; public Pair<double[], double[]> call(); public static int getNumberOfCalls(); @Override protected Pair<Double[], Double[]> computeRule(int order); public int getNumberOfCalls(); } ``` You are a professional Java test case writer, please create a test case named `testConcurrentCreation` for the `BaseRuleFactory` class, utilizing the provided abstract Java class context information and the following natural language annotations. ```java /** * Tests that a given rule rule will be computed and added once to the cache * whatever the number of times this rule is called concurrently. */ @Test public void testConcurrentCreation() throws InterruptedException, ExecutionException { ```
public abstract class BaseRuleFactory<T extends Number>
package org.apache.commons.math3.analysis.integration.gauss; import java.util.List; import java.util.ArrayList; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.math3.util.Pair; import org.junit.Test; import org.junit.Assert;
@Test public void testConcurrentCreation() throws InterruptedException, ExecutionException; public Pair<double[], double[]> call(); public static int getNumberOfCalls(); @Override protected Pair<Double[], Double[]> computeRule(int order); public int getNumberOfCalls();
bb86dee5d62c65c76761b509b2d28268218fbfc779c6bcbb6691ccefbbf587b2
[ "org.apache.commons.math3.analysis.integration.gauss.BaseRuleFactoryTest::testConcurrentCreation" ]
private final Map<Integer, Pair<T[], T[]>> pointsAndWeights = new TreeMap<Integer, Pair<T[], T[]>>(); private final Map<Integer, Pair<double[], double[]>> pointsAndWeightsDouble = new TreeMap<Integer, Pair<double[], double[]>>();
@Test public void testConcurrentCreation() throws InterruptedException, ExecutionException
private static final DummyRuleFactory factory = new DummyRuleFactory(); private static AtomicInteger nCalls = new AtomicInteger();
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.integration.gauss; import java.util.List; import java.util.ArrayList; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.math3.util.Pair; import org.junit.Test; import org.junit.Assert; /** * Test for {@link BaseRuleFactory}. * * @version $Id$ */ public class BaseRuleFactoryTest { /** * Tests that a given rule rule will be computed and added once to the cache * whatever the number of times this rule is called concurrently. */ @Test public void testConcurrentCreation() throws InterruptedException, ExecutionException { // Number of times the same rule will be called. final int numTasks = 20; final ThreadPoolExecutor exec = new ThreadPoolExecutor(3, numTasks, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2)); final List<Future<Pair<double[], double[]>>> results = new ArrayList<Future<Pair<double[], double[]>>>(); for (int i = 0; i < numTasks; i++) { results.add(exec.submit(new RuleBuilder())); } // Ensure that all computations have completed. for (Future<Pair<double[], double[]>> f : results) { f.get(); } // Assertion would fail if "getRuleInternal" were not "synchronized". final int n = RuleBuilder.getNumberOfCalls(); Assert.assertEquals("Rule computation was called " + n + " times", 1, n); } } class RuleBuilder implements Callable<Pair<double[], double[]>> { private static final DummyRuleFactory factory = new DummyRuleFactory(); public Pair<double[], double[]> call() { final int dummy = 2; // Always request the same rule. return factory.getRule(dummy); } public static int getNumberOfCalls() { return factory.getNumberOfCalls(); } } class DummyRuleFactory extends BaseRuleFactory<Double> { /** Rule computations counter. */ private static AtomicInteger nCalls = new AtomicInteger(); @Override protected Pair<Double[], Double[]> computeRule(int order) { // Tracks whether this computation has been called more than once. nCalls.getAndIncrement(); try { // Sleep to simulate computation time. Thread.sleep(20); } catch (InterruptedException e) { Assert.fail("Unexpected interruption"); } // Dummy rule (but contents must exist). final Double[] p = new Double[order]; final Double[] w = new Double[order]; for (int i = 0; i < order; i++) { p[i] = new Double(i); w[i] = new Double(i); } return new Pair<Double[], Double[]>(p, w); } public int getNumberOfCalls() { return nCalls.get(); } }
[ { "be_test_class_file": "org/apache/commons/math3/analysis/integration/gauss/BaseRuleFactory.java", "be_test_class_name": "org.apache.commons.math3.analysis.integration.gauss.BaseRuleFactory", "be_test_function_name": "addRule", "be_test_function_signature": "(Lorg/apache/commons/math3/util/Pair;)V", "line_numbers": [ "112", "113", "117", "118" ], "method_line_rate": 0.75 }, { "be_test_class_file": "org/apache/commons/math3/analysis/integration/gauss/BaseRuleFactory.java", "be_test_class_name": "org.apache.commons.math3.analysis.integration.gauss.BaseRuleFactory", "be_test_function_name": "convertToDouble", "be_test_function_signature": "(Lorg/apache/commons/math3/util/Pair;)Lorg/apache/commons/math3/util/Pair;", "line_numbers": [ "140", "141", "143", "144", "145", "147", "148", "149", "152" ], "method_line_rate": 1 }, { "be_test_class_file": "org/apache/commons/math3/analysis/integration/gauss/BaseRuleFactory.java", "be_test_class_name": "org.apache.commons.math3.analysis.integration.gauss.BaseRuleFactory", "be_test_function_name": "getRule", "be_test_function_signature": "(I)Lorg/apache/commons/math3/util/Pair;", "line_numbers": [ "58", "59", "64", "66", "70", "71", "74", "78" ], "method_line_rate": 0.875 }, { "be_test_class_file": "org/apache/commons/math3/analysis/integration/gauss/BaseRuleFactory.java", "be_test_class_name": "org.apache.commons.math3.analysis.integration.gauss.BaseRuleFactory", "be_test_function_name": "getRuleInternal", "be_test_function_signature": "(I)Lorg/apache/commons/math3/util/Pair;", "line_numbers": [ "95", "96", "97", "99", "101" ], "method_line_rate": 1 } ]